自定义eslint规则扩展

517 阅读1分钟

主要使用包 eslint-plugin-local-rules ^1.3.2

根目录配 eslint-local-rules.js

自定义规则 no-magic-number,不允许vue文件中出现魔法数字

module.exports = {
  'no-magic-number': require('./build/plugins/my-eslint-plugins/no-magic-number')
}

.eslintrc.js 增加rules

在.eslintrc.js 增加rules配置下面一条,可以error,warning等

'local-rules/no-magic-number': 'error'

no-magin-number.js

./build/plugins/my-eslint-plugins/no-magic-number 内容

VariableDeclarator,BinaryExpression,ObjectExpression 都来源于 astexplorer.net/ ,取type值然后根据json路径判断即可

const { isNumber } = require('lodash')
const isVue = path => /\.vue$/.test(path)
module.exports = {
  create: function(context) {
    const filename = context.getFilename()
    // 只处理vue文件
    if (!isVue(filename)) return {}
    return {
      /**
       * const a = 111
       */
      VariableDeclarator(node) {
        if (isNumber(node.init.value)) {
          context.report({
            node,
            message: '定义变量禁止直接使用数字'
          })
        }
      },
      /**
       * if( a === 222)
       */
      BinaryExpression(node) {
        if (isNumber(node.right.value)) {
          context.report({
            node,
            message: 'if判断中禁止直接使用数字'
          })
        }
      },
      /**
       * const b = { a: 111 }
       */
      ObjectExpression(node) {
        node.properties.some(property => {
          if (isNumber(property.value.value)) {
            context.report({
              node,
              message: '对象定义中禁止直接使用数字'
            })
            return true
          }
        })
      }
    }
  }
}