为了确保代码的转换严格匹配特定的模式,即在箭头函数中调用 require.ensure,并且确保箭头函数的参数是 r,我们需要对 ESLint 规则进行进一步的详细检查。这涉及到对 AST 节点的更精细控制和对上下文的检查。下面是一个符合这些要求的自定义 ESLint 规则。

定制 ESLint 规则

// 文件路径:eslint-rules/strict-require-ensure.js
module.exports = {
    meta: {
        type: "problem",
        docs: {
            description: "Strictly replace require.ensure in an arrow function with dynamic import",
            category: "ECMAScript 6",
            recommended: false
        },
        fixable: "code", // 表示该规则支持自动修复
        schema: [] // 空架构表示没有配置选项
    },

    create: function(context) {
        return {
            ArrowFunctionExpression(node) {
                // 确保箭头函数有一个参数且参数名为 r
                if (node.params.length === 1 && node.params[0].name === 'r') {
                    // 确保箭头函数体是一个 CallExpression
                    let body = node.body;
                    if (body.type === 'CallExpression' &&
                        body.callee.property &&
                        body.callee.property.name === 'ensure' &&
                        body.callee.object &&
                        body.callee.object.name === 'require') {
                        const [, callback, chunkNameNode] = body.arguments;

                        if (callback && callback.type === 'FunctionExpression' &&
                            chunkNameNode && chunkNameNode.type === 'Literal') {
                            const chunkName = chunkNameNode.value;
                            const requireCall = callback.body.body[0].expression.arguments[0];
                            const sourceCode = context.getSourceCode();
                            const pathLiteral = sourceCode.getText(requireCall.arguments[0]);

                            context.report({
                                node: body,
                                message: 'Use dynamic import() instead of require.ensure()',
                                fix: fixer => {
                                    const newCode = `() => import(/* webpackChunkName: "${chunkName}" */ ${pathLiteral})`;
                                    return fixer.replaceText(node, newCode);
                                }
                            });
                        }
                    }
                }
            }
        };
    }
};

说明

这个规则检查以下条件:

  1. 箭头函数定义:只有一个参数,且该参数名为 r
  2. 函数体:必须是 require.ensure 的调用。
  3. require.ensure 的结构:检查 require.ensure 调用以确保它符合特定的模式,包括参数和代码块名称。

在 ESLint 配置中启用规则

确保你的 ESLint 配置文件引入了自定义规则并启用它:

{
    "plugins": [
        "local-rules"
    ],
    "rules": {
        "local-rules/strict-require-ensure": "error"
    },
    "overrides": [{
        "files": ["*.js", "*.jsx", "*.ts", "*.tsx", "*.vue"],
        "processor": "local-rules/strict-require-ensure"
    }]
}

运行 ESLint

使用以下命令应用规则并自动修复代码:

npx eslint src/ --fix

通过这种方法,你可以确保只有符合特定条件的 require.ensure 调用被转换为新的 import() 语法。这样的严格检查可以帮助确保代码的转换准确无误,避免对不应修改的代码进行更改。

博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3