无法加载typescript-eslint创建的ESLint规则,求排查原因
自定义TypeScript-ESLint规则无法加载的排查方案
问题描述
使用typescript-eslint创建了一条ESLint规则,规则项目的依赖、tsconfig配置如下。经tsc编译后安装到目标项目,且目标项目的.eslintrc.js已配置引入对应插件与规则,但自定义规则始终无法加载。
规则项目package依赖
{ "devDependencies": { "@types/node": "^18.14.6", "@typescript-eslint/eslint-plugin": "^5.54.1", "@typescript-eslint/parser": "^5.54.1", "eslint": "^8.35.0", "prettier": "^2.8.4", "ts-node": "^10.9.1", "typescript": "^4.9.5" }, "dependencies": { "@typescript-eslint/utils": "^5.54.1" } }
规则项目tsconfig配置
{ "compilerOptions": { "target": "es2016", "module": "commonjs", "moduleResolution": "node", "outDir": "./build", "sourceRoot": "", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true }, "include": ["./*.ts"] }
目标项目.eslintrc.js配置
module.exports = { env: { browser: true, es6: true, commonjs: true, "amd": true, "node": true }, extends: "eslint:recommended", overrides: [], parserOptions: { ecmaVersion: 7, sourceType: "module", }, plugins: ["translation"], rules: { "translation/check-length": [2, { min: 3 }], }, };
可能的原因及排查方向
- 插件入口未配置:规则项目的
package.json缺少main字段,未指向编译后的入口文件(如build/index.js),导致ESLint无法找到插件入口。 - 编译产物不完整:检查
tsc编译后的build目录,确认规则代码已生成;若规则文件放在子目录,当前include: ["./*.ts"]未覆盖子目录文件,需调整为include: ["**/*.ts"]。 - 插件命名不规范:ESLint插件要求包名必须以
eslint-plugin-开头,引用时可省略前缀。若规则项目包名不是eslint-plugin-translation,目标项目plugins: ["translation"]会匹配失败——要么修改包名,要么在plugins中填写完整包名,或在规则项目package.json中配置eslint-plugin字段指定插件ID。 - 依赖版本不兼容:目标项目的ESLint、@typescript-eslint系列依赖版本与规则项目差异过大,导致加载失败。需确保目标项目的ESLint、@typescript-eslint/utils等核心依赖版本与规则项目匹配。
- 目标项目解析器配置缺失:自定义规则基于TypeScript-ESLint开发,目标项目需配置
@typescript-eslint/parser作为解析器。当前目标项目仅继承eslint:recommended,缺少TypeScript解析器配置,需补充:parser: "@typescript-eslint/parser", - 本地安装路径异常:若使用
npm link本地安装,可能存在符号链接解析问题,尝试改用npm install ../path-to-rule-project直接本地安装。
内容的提问来源于stack exchange,提问作者Masquitos
相关产品推荐
相关产品推荐

