最近小编被eslint所困扰,不得不去官网去浏览,去各种的查资料,花费了一两天的时间,终于懂的了eslint的配置,
下载插件
- 在vscode中,下载Vetur、Prettier - Code formatter、ESLint
- 在settings.json中
// 在设置--》settings.json中设置
//eslint配置
//autoFixedOnSave 设置已废弃,采用如下新的设置
"editor.codeActionsOnSave": {
// For ESLint and StyleLint
"source.fixAll": true
},
"eslint.format.enable": true,
//autoFix默认开启,只需输入字符串数组即可
"eslint.validate": [
"javascript",
"javascriptreact",
"vue",
"html",
"typesctipt",
"typescriptreact"
],
"[vue]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"editor.tabSize": 2,
"[jsonc]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
如果你以前安装过JS的格式化工具,需要删除掉,
"[javascript]": {
"editor.defaultFormatter": "HookyQR.beautify"
}
因为,它会和下面的配置重复
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
在 .eslintrc.js中配置
如果不是使用vue-cli创建的项目,就需要自己创建 .eslintrc.js
module.exports = {
env: {
browser: true,
es6: true,
node: true
},
root: true,
extends: "standard",
parser: "babel-eslint",
plugins: ["html", "vue"],
rules: {
semi: "off",
"arrow-parens": 0,
"array-callback-return": 0,
curly: 1,
"no-void": 0,
"no-eval": 2,
"no-unused-vars": [
"warn",
{
vars: "local",
args: "none",
ignoreRestSiblings: false
}
],
indent: [
"error",
2,
{
SwitchCase: 1
}
],
"eol-last": 0,
"space-before-function-paren": 0,
"no-useless-escape": 0,
"spaced-comment": 0,
"arrow-spacing": 0,
"no-multiple-empty-lines": 0,
"brace-style": "warn",
quotes: "warn",
"padded-blocks": 0,
camelcase: "warn"
}
};
package.json中配置
// 需要安装以下配置
"eslint": "^6.8.0",
"eslint-config-standard": "^14.1.1",
"eslint-loader": "^4.0.2",
"eslint-plugin-html": "^6.0.3",
"eslint-plugin-import": "^2.22.0",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-standard": "^4.0.1",
"eslint-plugin-vue": "^6.2.2",
"husky": "^4.2.5",
"vue-cli-plugin-element": "~1.0.1",
"vue-template-compiler": "^2.6.11"
- 安装如下
npm i eslint eslint-config-standard eslint-plugin-st
andard eslint-plugin-promise eslint-plugin-import eslint-plugin-node -D
//去识别script标签中的javascript
npm i eslint-plugin-html -D
//为了可以自动改动,
npm i eslint-loader babel-eslint -D
//为了使代码更加,使用一个钩子,在调用命令的时候,可以自动检测代码
npm i husky -D //具体的配置在npm官网上husky
"scripts": {
"lint": "eslint src"
/*"lint": " lint,eslint --ext .jsx --ext .js src/",
"lint-fix": "lint,eslint --fix --ext .jsx --ext .js src/"*/
},
"hooks": {
"pre-commit": "npm lint",
}
//也可以设置如下配置
"prettier": {
"stylelintIntegration": true,
"eslintIntegration": true
},
以下为可选,参考
在.editorconfig中进行一些规范
root = true # 让其读到这个目录
[*]
charset = utf-8
end_of_line = lf
indent_size = 2 # 长度为2
indent_style = space
insert_final_newline = true # 自动加空行
trim_trailing_whitespace = true # 自动去空格
- 还可以在vue-cli中webpack配置中,进行如下配置
rules: [
//在进行vue-loader之前,先进行代码检查
{
test: /\(vue|js|jsx)$/,
loader: 'eslint-loader',
excludes: /node_modules/,
enforce:'pre'
},
{
test: /\.vue$/,
loader: 'vue-loader'
},
]