Eslint:如何使用 rc 配置文件格式解析本地插件或规则?

问题描述 投票:0回答:1

Eslint v8.50,使用 eslintrc.js 配置格式

我正在按照 自定义规则教程 创建自定义规则(据我所知,这需要一个插件),但我无法导入我的本地插件。

尝试以下:

  • 按照教程提供对象:不支持对象,需要字符串
  • 尝试提供我的插件的路径:出现
    Plugins array cannot includes file paths
    错误
  • 在项目根目录中使用
    eslint-plugin-example
    创建
    index.js
    目录(在
    eslintrc.js
    旁边),并在插件配置中提供“eslint-plugin-example”:未找到配置

我设法使其工作的唯一方法是执行

npm i ./eslint-plugin-example --save-dev
,它在
node_modules
中创建了符号链接。对于包括本地规则/插件这样简单的事情来说,这感觉太复杂了。

还有其他方法可以实现吗? (无需迁移到平面配置)

javascript eslint eslintrc
1个回答
0
投票

我也没有找到其他解决方案,但效果很好。

文件结构:

file structure

eslint-plugin-custom/index.js:

module.exports = {
    rules: {
      'my-custom-rule': require('./rules/my-custom-rule')
    }
  };
  

eslint-plugin-custom/package.json(需要作为包安装):

{
  "name": "eslint-plugin-custom",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}
  

eslint-plugin-custom/rules/my-custom-rule.js(用您的规则替换代码):

module.exports = {
    meta: {
      type: 'problem',
      docs: {
        description: 'disallow the use of console.log',
        category: 'Best Practices',
        recommended: false
      },
      schema: [], // no options
    },
    create: function(context) {
      return {
        CallExpression(node) {
          if (node.callee.object && node.callee.object.name === 'console' && node.callee.property.name === 'log') {
            context.report({
              node,
              message: 'Unexpected console.log statement.'
            });
          }
        }
      };
    }
  };
  

eslintrc.json 中的更新:

{
  ...
  "plugins": [
    ...,
    "custom"
  ],
  "overrides": [
    ...
    {
      ...
      "rules": {
        ...
        "custom/my-custom-rule": "error"
      }
    }
  ]
}
  

安装命令:

npm i .\eslint-plugin-custom --save-dev
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.