eslint规则,识别import("XXX")

Posted on 2024-05-17 09:26  生之不止,思之不息  阅读(53)  评论(0)    收藏  举报

在 ESLint 规则中,你可以使用 AST(抽象语法树)解析来识别类似 import("@/components/BaseIcon") 的语句,并提取其中的路径。以下是一个自定义 ESLint 规则的示例代码,它会识别这种 import 语句并提取路径。

首先,你需要创建一个自定义的 ESLint 规则文件。例如,创建一个名为 extract-import-path.js 的文件:

module.exports = {
  meta: {
    type: "suggestion",
    docs: {
      description: "Extract import paths",
      category: "Best Practices",
      recommended: false,
    },
    schema: [], // no options
  },
  create(context) {
    return {
      ImportDeclaration(node) {
        const importPath = node.source.value;
        if (importPath.startsWith('@/')) {
          context.report({
            node,
            message: `Import path detected: ${importPath}`,
          });
        }
      },
      'CallExpression[callee.name="import"]'(node) {
        if (node.arguments[0] && node.arguments[0].type === 'Literal') {
          const importPath = node.arguments[0].value;
          if (importPath.startsWith('@/')) {
            context.report({
              node,
              message: `Dynamic import path detected: ${importPath}`,
            });
          }
        }
      }
    };
  },
};

接下来,你需要在你的 ESLint 配置文件中启用这个规则。例如,在 .eslintrc.js 文件中添加以下内容:

module.exports = {
  // 其他配置
  rules: {
    'extract-import-path/extract-import-path': 'warn',
  },
  plugins: [
    'extract-import-path',
  ],
  settings: {
    'import/resolver': {
      alias: {
        map: [
          ['@', './src'],
        ],
        extensions: ['.ts', '.js', '.jsx', '.json']
      }
    }
  }
};

最后,你需要确保 ESLint 能够找到你的自定义规则。你可以在 ESLint 配置文件的 plugins 部分中添加自定义规则所在的目录。例如:

module.exports = {
  // 其他配置
  plugins: [
    'extract-import-path',
  ],
  rules: {
    'extract-import-path/extract-import-path': 'warn',
  },
};

这样,当你运行 ESLint 时,它会检测 import("@/components/BaseIcon") 的语句并提取其中的路径。你可以根据需要修改规则的行为,例如,将路径提取到某个数据结构中,或者执行其他操作。

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