VSCode配置ESLint和Prettier插件
1.安装扩展程序
2.配置settings.json
- 按下Ctrl+Shift+P,查找settings
- 设置ESLint和Prettier配置
{
"editor.formatOnSave": true, // 值设置为true时,每次保存的时候自动格式化
"editor.defaultFormatter": "esbenp.prettier-vscode", //默认格式化程序 prettier //prettier 配置代码格式化
"prettier.enable": true, //启用prettier
"prettier.singleQuote": true, //使用单引号
"prettier.trailingComma": "none", //末尾不加逗号
"prettier.semi": true, //末尾添加分号
"prettier.arrowParens": "avoid", //箭头函数只有一个参数时,是否需要括号
"prettier.printWidth": 150, //每行代码最佳长度,超过就换行 // ESLint 配置代码检查
"eslint.enable": true, //启用eslint
"eslint.format.enable": false, //不使用过eslint进行格式化
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true // 启用 eslint 自动修复
}
}
3.配置项目使用的ESLint设置
- 项目根目录建立.eslintrc.js文件
- 使用npm安装eslint和用到的插件
- 在文件中配置当前项目的ESLint规则
module.exports = {
root: true,
env: {
browser: true,
es6: true
},
plugins: [
'html' //eslint-plugin-html插件,用于处理HTML文件中的js
],
rules: {
semi: ['error', 'always'], //末尾添加分号
quotes: ['error', 'single'], //单引号
eqeqeq: 'error', //等于使用 ===相等
'no-dupe-args': 2, //函数参数禁止重名
'no-dupe-keys': 2, //对象字面量禁止使用重复的key
'no-duplicate-case': 2, //在switch语句中禁止重复的case
'no-eval': 2, //禁止使用eval函数
'no-extra-boolean-cast': 2, //在一个本来就会自动转化为布尔值的上下文中就没必要再使用!! 进行强制转化了
'no-new-object': 2, //不要通过new Object(),来定义对象
'no-new-wrappers': 2, //当定义字符串、数字、布尔值就不要使用构造函数了,String、Number、Boolean
'no-obj-calls': 2, //禁止无意得把全局对象当函数调用了,比如下面写法错误的:Math(), JSON()
'no-redeclare': 2, //不要重复申明一个变量
//禁止使用没有必要的三元操作符,因为用些三元操作符可以使用其他语句替换
'no-unneeded-ternary': [
2,
{
defaultAssignment: false
}
],
'no-unreachable': 2, //执行不到的代码
'use-isnan': 1, //推荐使用isNaN方法,而不要直接和NaN作比较
camelcase: 1, //变量和函数的名字使用 camelCase 格式
'no-unused-vars': 1, //定义未使用的变量给警告
'no-array-constructor': 1, //使用对象字面量,不使用对象构造函数
'no-const-assign': 1, //不要修改由 const 声明的变量
'no-debugger': 1, //不使用 debugger 语句。
'no-ex-assign': 2, //catch 语句中不要对错误对象重新赋值
'no-floating-decimal': 1, //浮点数应包含整数和小数
'no-func-assign': 2, //不给声明过的函数重新赋值
'no-global-assign': 2, //不给只读的全局变量重新赋值
'no-implied-eval': 2, //不使用隐式 eval()
'no-inner-declarations': 2, //不在嵌套语句中使用函数声明
'no-lone-blocks': 1 //不使用非必要的嵌套语句块
}
};