You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

是否存在ESLint规则可避免分散的require()分组并合并同路径引用?

实现ESLint检测并合并同路径重复require的方案

方案一:使用eslint-plugin-import的no-duplicates规则(推荐)

这是最简便的实现方式,该规则支持检测CommonJS的重复require语句,并提供自动修复能力。

  1. 安装依赖
npm install eslint-plugin-import --save-dev
  1. 配置ESLint规则
    在你的ESLint配置文件(如.eslintrc.js或.eslintrc.json)中添加以下配置:
{
  "plugins": ["import"],
  "rules": {
    "import/no-duplicates": ["warn", {
      "commonjs": true, // 开启对CommonJS require语句的检测
      "includeExports": false // 仅关注导入逻辑,忽略导出重复的检测
    }]
  }
}
  1. 效果说明
  • 检测告警:当代码中出现同一路径的多次require时,ESLint会发出警告,提示Duplicate import './my/path.js'
  • 自动修复:运行eslint --fix命令后,会自动合并同路径的解构声明,将你的示例代码修复为:
const { a, b, c, f } = require('./my/path.js');

const {d, e} = require('./my/other/path2.js');

方案二:自定义ESLint规则(适合特殊定制需求)

如果现有插件无法满足你的个性化逻辑,可以编写自定义规则实现更精细的控制。

步骤1:编写自定义规则

创建规则文件(如rules/no-duplicate-requires.js),核心逻辑是跟踪所有require调用的路径,检测重复并提供合并修复:

module.exports = {
  meta: {
    type: 'suggestion',
    docs: {
      description: '禁止同一模块路径被多次require',
      category: '最佳实践',
      recommended: true
    },
    fixable: 'code',
    schema: []
  },
  create(context) {
    const requireMap = new Map(); // key: 模块路径, value: { 声明节点, 解构属性集合 }

    return {
      VariableDeclarator(node) {
        // 匹配 const { ... } = require('xxx') 的结构
        if (node.init?.type === 'CallExpression' && node.init.callee.name === 'require') {
          const pathNode = node.init.arguments[0];
          if (!pathNode || pathNode.type !== 'Literal') return; // 仅处理静态字符串路径
          const modulePath = pathNode.value;

          // 提取当前解构的属性名
          const currentProps = node.id.type === 'ObjectPattern' 
            ? new Set(node.id.properties.map(p => p.key.name)) 
            : new Set();

          if (requireMap.has(modulePath)) {
            // 检测到重复require,报告错误并生成修复方案
            const existingEntry = requireMap.get(modulePath);
            context.report({
              node,
              message: `重复引入模块:${modulePath}`,
              fix(fixer) {
                // 合并属性到已有声明
                const mergedProps = [...existingEntry.props, ...currentProps];
                const newIdText = `{ ${mergedProps.join(', ')} }`;
                return [
                  fixer.replaceText(existingEntry.node.id, newIdText),
                  fixer.remove(node.parent) // 删除重复的声明行
                ];
              }
            });
          } else {
            // 记录首次出现的require
            requireMap.set(modulePath, {
              node,
              props: currentProps
            });
          }
        }
      }
    };
  }
};

步骤2:配置自定义规则

在ESLint配置中引入自定义规则(假设你的插件名为custom-eslint-rules):

{
  "plugins": ["custom-eslint-rules"],
  "rules": {
    "custom-eslint-rules/no-duplicate-requires": "warn"
  }
}

注意:自定义规则需要处理更多边缘场景(如非解构的require、动态路径等),上述示例为基础实现,可根据需求扩展。

内容的提问来源于stack exchange,提问作者Clau

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 20:15:31