在项目中使用自定义 eslint 插件

74 阅读1分钟

在项目中使用自定义 eslint 插件

编写本地插件

创建插件文件模块

.
├── src
└── eslint-plugin-check-vue-methods-function-name
    ├── index.js
    └── package.json

index.js

module.exports = {
  rules: {
    'method-name-comment': {
      meta: {
        docs: {
          description: '要求 Vue 单文件组件中 methods 中的方法名必须有注释',
          category: 'Best Practices',
          recommended: true
        },
        fixable: false
      },
      create(context) {
        const filePath = context.getFilename()
        if (!filePath.endsWith('.vue')) {
          return
        }

        // 其余的规则检查逻辑
        const vueScript = context.getSourceCode().ast.body.find(node => node.type === 'ExportDefaultDeclaration' && node.declaration.type === 'ObjectExpression')
        if (vueScript) {
          const methodsProperty = vueScript.declaration.properties.find(prop => prop.key.name === 'methods')
          if (methodsProperty) {
            const methodsObject = methodsProperty.value
            if (methodsObject.type === 'ObjectExpression') {
              methodsObject.properties.forEach(method => {
                if (typeof method.key.name === 'string' && !method.leadingComments) {
                  context.report({
                    node: method,
                    message: 'Vue 单文件组件 methods 中的方法名必须有注释'
                  })
                }
              })
            }
          }
        }

        return {}
      }
    }
  }
}

package.json

{
  "name": "eslint-plugin-check-vue-methods-function-name",
  "version": "1.0.0",
  "main": "index.js"
}

安装本地插件

在项目根目录的 package.json 的 devDependencies 部分添加:

  "eslint-plugin-check-vue-methods-function-name": "file:eslint-plugin-check-vue-methods-function-name",

执行安装命令:

npm i eslint-plugin-check-vue-methods-function-name -D

配置 .eslintrc.js 文件

添加插件:

plugins: ["check-vue-methods-function-name"],

配置规则:

rules: {
  "check-vue-methods-function-name/method-name-comment": 2,
}