如何在Eslint v8.50的eslintrc.js配置中引入本地插件或规则?
ESLint v8.x(非Flat Config)本地插件简化引入方案
以下是几种无需迁移到Flat Config的简化方法,解决本地ESLint插件的引入问题:
方法1:利用NODE_PATH环境变量指定加载目录
通过设置NODE_PATH让Node.js识别本地插件目录,无需修改插件结构:
- 在项目根目录创建存放本地插件的文件夹,比如
local-plugins,将你的eslint-plugin-example目录放入其中 - 在启动ESLint时指定
NODE_PATH,或者把命令写入package.json的scripts:# 直接执行 NODE_PATH=./local-plugins eslint . # 或在package.json中配置 { "scripts": { "lint": "NODE_PATH=./local-plugins eslint ." } } - 在
eslintrc.js中正常配置插件:module.exports = { plugins: ["example"], // 对应插件目录名eslint-plugin-example rules: { "example/your-custom-rule": "error" } };
方法2:在配置文件中直接加载插件对象
如果之前传入插件对象失败,大概率是插件格式不符合要求,正确做法:
- 确保本地插件的
index.js导出包含name属性的对象:// ./eslint-plugin-example/index.js module.exports = { name: "example", // ESLint依赖此属性识别规则前缀 rules: { "your-custom-rule": { create(context) { // 自定义规则逻辑 } } } }; - 在
eslintrc.js中直接引入并注册插件:const examplePlugin = require("./eslint-plugin-example"); module.exports = { plugins: [examplePlugin], rules: { "example/your-custom-rule": "error" } };
方法3:使用npm link快速链接本地插件
比本地install软链接更灵活,修改插件后无需重新安装:
- 进入本地插件目录
./eslint-plugin-example,执行:npm link - 回到项目根目录,执行:
npm link eslint-plugin-example - 在
eslintrc.js中正常配置插件即可:module.exports = { plugins: ["example"], rules: { "example/your-custom-rule": "error" } };
内容的提问来源于stack exchange,提问作者Pavel Gurecki
相关产品推荐
相关产品推荐

