vue项目中使用eslint+prettier规范与检查代码的方法

2020-06-16 06:36:38易采站长站整理

'use-isnan': 2, //禁止比较时使用NaN,只能用isNaN()
'valid-typeof': 2, //必须使用合法的typeof的值
'wrap-iife': [2, 'any'], //立即执行函数表达式的小括号风格
'yield-star-spacing': [2, 'both'], // 强制执行*周围 yield*表达式的间距,两侧都必须有空格
'yoda': [2, 'never'],
'prefer-const': 2, // 使用let关键字声明的变量,但在初始分配后从未重新分配变量,应改为const声明
'object-curly-spacing': [2, 'always', { objectsInObjects: false }],// 不允许以对象元素开始和/或以对象元素结尾的对象的大括号内的间距
'array-bracket-spacing': [2, 'never'] // 不允许数组括号内的空格
}
}

2.2 eslint 安装与配置

全局安装 eslint


npm install -g eslint

全局安装 Prettier


npm install -g prettier

vscode 插件市场搜索 eslint 和 prettier,下载并安装。

vscode

编辑器 setting.json 中加如下配置:


/* 开启保存时自动格式化 */
"editor.formatOnSave": true,

/* eslint的配置 */
"eslint.enable": true,
"eslint.run": "onSave",
"eslint.options": {
"extensions": [
".js",
".vue"
] },
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true // 保存时自动修复
},
// 关闭 vscode 默认的检查工具
"html.validate.scripts": false,
"javascript.validate.enable": false,
"eslint.alwaysShowStatus": true,
"eslint.format.enable": true,
"scss.lint.duplicateProperties": "error",
"css.lint.duplicateProperties": "error",
"less.lint.zeroUnits": "error",
"eslint.validate": [
"javascript",
"javascriptreact",
"vue-html",
"vue",
"html"
],

/* prettier的配置 */
"prettier.printWidth": 120, // 超过最大值换行
"prettier.tabWidth": 2, // 缩进字节数
"prettier.useTabs": true, // 缩进使用tab
"prettier.semi": false, // 句尾添加分号
"prettier.singleQuote": true, // 使用单引号代替双引号
"prettier.proseWrap": "preserve", // 默认值。因为使用了一些折行敏感型的渲染器(如GitHub comment)而按照markdown文本样式进行折行
"prettier.arrowParens": "avoid", // (x) => {} 箭头函数参数只有一个时是否要有小括号。avoid:省略括号
"prettier.bracketSpacing": true, // 在对象,数组括号与文字之间加空格 "{ foo: bar }"
"prettier.endOfLine": "auto", // 结尾是 n r nr auto