写一个继承于@angular-eslint的自定义eslint插件

588 阅读2分钟

一起写一个名为@my-custom/eslint-plugin的自定义eslint插件吧 :)

用这个自定义插件,我们可以

  • 继承/使用其他插件的规则(这里使用@angular-eslint为例子,将分别重写templatetypescript中的规则)
  • 自定义规则
  • 共享给其他项目使用 下面会从写插件,测试插件两步分别描述(不涉及publish)。

写插件

  1. 新建项目,e.g. my-custom-eslint-plugin

  2. 生成package.json(对于 npm 可能在命令行上打印的任何提示,自动回答"是"。)

npm init -y
  1. package.json生成如下
{
  "name": "my-custom-eslint-plugin",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}
  1. package.jsonname中填入插件名字@my-custom/eslint-plugin以及depedencies(其他按需填入)
{
  "name": "@my-custom/eslint-plugin",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
       "eslint": "8.7.0",
       "@angular-eslint/eslint-plugin": "13.0.1",
       "@angular-eslint/eslint-plugin-template": "13.0.1",
       "@angular-eslint/template-parser": "13.0.1",
       "@typescript-eslint/eslint-plugin": "5.10.1",
       "@typescript-eslint/parser": "5.10.1"
  }
}
  1. 安装依赖包
npm install
  1. 根目录下手动创建index.js,定义所需继承extends的插件信息@angular-eslint和自定义的规则rules(这里为了举例,改写了@angular-eslint/no-empty-lifecycle-method@angular-eslint/template/no-negated-async规则),如下:
module.exports = {
    configs: {
        'angular-typescript': {
            env: {
                browser: true,
                es6: true,
                node: true
            },
            plugins: ['@angular-eslint'],
            extends: ['plugin:@angular-eslint/recommended'],
            rules: {
                '@angular-eslint/no-empty-lifecycle-method': 'warn'
            }
        },
        'angular-template': {
            plugins: ['@angular-eslint/template'],
            extends: ['plugin:@angular-eslint/template/recommended'],
            rules: {
                '@angular-eslint/template/no-negated-async': 'warn'
            }
        }
    }
};

本地测试

1. 环境搭建

为了在本地其他项目中可找到名为@my-custom/eslint-plugin的包,在以上my-custom-eslint-plugin插件项目中运行命令行:

npm link

在需要加载这个@my-custom/eslint-plugin插件的项目中,运行以下命令:

npm link @my-custom/eslint-plugin

2. 配置.eslintrc.json

可在overrides中为ts文件和html文件分别配置自定义插件规则@my-custom/angular-typescript@my-custom/angular-template,例子如下:

{
  "root": true,
  "ignorePatterns": ["!**/*"],
  "plugins": ["@my-custom"],
  "overrides": [
    {
      "files": ["*.ts"],
      "parserOptions": {
        "project": ["tsconfig.json"],
        "createDefaultProgram": true
      },
      "extends": ["plugin:@my-custom/angular-typescript"]
    },
    {
      "files": ["*.html"],
      "extends": ["plugin:@my-custom/angular-template"]
    }
  ]
}

3. 运行eslint

如为Angular项目,运行以下命令行

ng lint

在其他项目中正式使用

在将自定义插件publish后,其他项目也可以直接使用了,只需在devDependencies中声明该插件:

"@my-custom/eslint-plugin": "1.0.0"