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

自定义ESLint规则修复器:未导入时自动添加辅助函数导入

ESLint自动修复实现getStringValue自动导入的最佳方案

核心思路

你可以直接通过ESLint提供的context.getSourceCode()获取完整源码对应的AST根节点,无需重新解析文本。基于这个根节点就能遍历检测导入状态,再结合修复器完成三种导入场景的处理。

步骤分解

1. 检测现有导入状态

在规则的create方法中,先遍历AST的ImportDeclaration节点,判断当前文件的导入情况:

  • 若已存在import { getStringValue } from '你的工具模块路径'这类声明,直接跳过导入逻辑;
  • 若已导入目标模块但未包含getStringValue,比如import { otherFunc } from '你的工具模块路径',则修改该导入节点添加目标函数;
  • 若模块和函数都未导入,在文件顶部插入全新的导入语句。

2. 具体实现代码

首先获取AST根节点:

const sourceCode = context.getSourceCode();
const rootNode = sourceCode.ast;

编写导入状态检测函数:

function checkImportStatus(rootNode, targetModule, targetFunc) {
  let importDecl = null;
  let hasTargetFunc = false;

  for (const node of rootNode.body) {
    if (node.type === 'ImportDeclaration' && node.source.value === targetModule) {
      importDecl = node;
      hasTargetFunc = node.specifiers.some(spec => 
        spec.type === 'ImportSpecifier' && spec.local.name === targetFunc
      );
      break;
    }
  }

  return { importDecl, hasTargetFunc };
}

在修复器中结合检测结果处理:

fixer => {
  const targetModule = '你的工具模块路径'; // 替换为实际模块路径
  const targetFunc = 'getStringValue';
  const { importDecl, hasTargetFunc } = checkImportStatus(rootNode, targetModule, targetFunc);
  const fixes = [];

  // 替换原函数调用
  fixes.push(fixer.replaceText(node, `${targetFunc}(${identifierNode.getText()})`));

  // 处理导入逻辑
  if (!hasTargetFunc) {
    if (importDecl) {
      // 已有模块导入,追加目标函数到导入列表
      const lastSpecifier = importDecl.specifiers[importDecl.specifiers.length - 1];
      fixes.push(fixer.insertTextAfter(lastSpecifier, `, ${targetFunc}`));
    } else {
      // 无模块导入,插入全新导入语句
      const firstNode = rootNode.body[0];
      const importText = `import { ${targetFunc} } from '${targetModule}';\n`;
      fixes.push(fixer.insertTextBefore(firstNode, importText));
    }
  }

  return fixes;
}

3. 注意事项

  • 导入语句插入位置尽量放在所有现有导入的最前面,避免触发import/order类规则报错;
  • 如果项目使用默认导入或命名空间导入(比如import Utils from 'xxx'),需要额外调整逻辑适配;
  • 要考虑代码风格一致性,比如导入列表的逗号格式( trailing comma)是否符合项目规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 17:02:37