ESlint 配置使用指南

9,216 阅读2分钟

ESLint 是一个开源的 JavaScript 代码检查工具,它是用来进行代码的校验,检测代码中潜在的问题,比如某个变量定义了未使用、函数定义的参数重复、变量名没有按规范命名等等。

VSCode 可以直接安装插件:vscode-eslint

规则:

ESLint 附带有大量的规则,修改规则应遵循如下要求:

'off' 或 0 - 关闭规则
'warn' 或 1 - 开启规则,使用警告级别的错误:warn (不会导致程序退出)
'error' 或 2 - 开启规则,使用错误级别的错误:error (当被触发的时候,程序会退出)

使用方法:

安装依赖

"eslint": "^6.7.2",    
"eslint-plugin-vue": "^6.2.2",    
"eslint-plugin-import": "^2.20.2",    
"eslint-plugin-node": "^11.1.0",    
"eslint-plugin-promise": "^4.2.1",    
"eslint-plugin-standard": "^4.0.0"

在项目根目录创建 .eslintrc.js 文件 

里面 常规配置如下:

// .eslintrc.js
module.exports = {    
    root: true,    
    env: {      
        node: true    
    },    
    extends: [      
        'plugin:vue/essential'    
    ],    
    plugins: ['vue'],    
    parserOptions: {      
        parser: 'babel-eslint'    
    },    
    rules: {      
        // 禁用 alert、confirm、prompt、console、debugger      
        'no-alert': process.env.NODE_ENV === 'production' ? 'warn' : 'off',      
        'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',      
        'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',      
        'eqeqeq':'warn',  // 要求使用 === 和 !==      
        'no-dupe-args': 'error', // 禁止 function 定义中出现重名参数      
        'no-dupe-keys': 'error', // 禁止对象字面量中出现重复的 key      
        'no-eval': 'error', // 禁用 eval()      
        'no-self-compare': 'error', // 禁止自身比较      
        'no-self-assign': 'error', // 禁止自我赋值      
        'no-unused-vars': 'error',  // 禁止出现未使用过的变量      
        'no-const-assign': 'error',  // 禁止修改 const 声明的变量      
        'no-func-assign': 'error',  // 禁止对 function 声明重新赋值      
        'camelcase': 'error',  // 强制使用骆驼拼写法命名约定      
        'no-mixed-spaces-and-tabs': 'error', //禁止混用tab和空格      
        'indent': ['warn', 2], //缩进风格这里不做硬性规定,但是产品组内要达成统一      
        'quotes': ['warn', 'single'], //要求引号类型 `` ' ''      
        'semi': ['error', 'always'], //语句强制分号结尾    
    }  
}

然后

vue-cli3vue.config.jslint打开 lintOnSave:true

接下来就是在vscode中设置的事了

打开vscode ,搜索插件 eslint

安装插件

安装好了重新打开项目就能用了哦