vscode安装eslint插件,代码统⼀⾃动修复
ESlint:是⽤来统⼀JavaScript代码风格的⼯具,不包含css、html等。
⽅法和步骤:
通常情况下vue项⽬都会添加eslint组件,我们可以查看webpack的配置⽂件package.json查看,也可以查看⼯程下是否有.eslintrc.js
和.eslintignore查看到eslint是否开启。
当我们编写不符合eslint规范的代码时,启动项⽬会报错,⽐如
这个时候可以安装vscode eslint插件,就可以⾃动检测不符合规范的代码。打开vscode左侧扩展⾯板,搜索eslint,点击安装,重启后⽣效
安装好之后,还需要在vscode⽂件中进⾏设置:
通过  file->preferences->Settings 出现如下界⾯:
点击红框,则会出现配置⽂件
把以下代码复制到这个⽂件中:
{
// vscode默认启⽤了根据⽂件类型⾃动设置tabsize的选项
"editor.detectIndentation": false,
// 重新设定tabsize
"editor.tabSize": 2,
// #每次保存的时候⾃动格式化
"editor.formatOnSave": true,
// #每次保存的时候将代码按eslint格式进⾏修复
"eslint.autoFixOnSave": true,
// 添加 vue ⽀持
"eslint.validate": [
"javascript",
"javascriptreact",
{
"language": "vue",
"autoFix": true
}
],
//  #让prettier使⽤eslint的代码格式进⾏校验
"prettier.eslintIntegration": true,
//  #去掉代码结尾的分号
"prettier.semi": false,
//  #使⽤带引号替代双引号
"prettier.singleQuote": true,
//  #让函数(名)和后⾯的括号之间加个空格
"javascript.format.insertSpaceBeforeFunctionParenthesis": true,
// #让vue中的js按编辑器⾃带的ts格式进⾏格式化
"vetur.format.defaultFormatter.js": "vscode-typescript",
"vetur.format.defaultFormatterOptions": {
"js-beautify-html": {
"wrap_attributes": "force-aligned"
// #vue组件中html代码格式化样式
}
},
"Level": 0,
"firmDelete": false,
"firmDragAndDrop": false,
"derControlCharacters": true,
"derWhitespace": "all"
}
然后在项⽬的.eslintrc.js中添加如下代码:
// /docs/user-guide/configuring
root: true,
parserOptions: {
vscode代码规范parser: 'babel-eslint'
},
env: {
browser: true
},
extends: [
// github/vuejs/eslint-plugin-vue#priority-a-essential-error-prevention
// consider switching to `plugin:vue/strongly-recommended` or `plugin:vue/recommended` for stricter rules.    'plugin:vue/essential',
// github/standard/standard/blob/master/docs/RULES-en.md
'standard'
],
// required to lint *.vue files
plugins: ['vue'],
// add your custom rules here
rules: {
// allow async-await
'no-console': 'off',
indent: ['error', 2, { SwitchCase: 1 }],
semi: ['error', 'always'],
'space-before-function-paren': [
'error',
{ anonymous: 'always', named: 'never' }
],
'generator-star-spacing': 'off',
// allow debugger during development
'no-debugger': v.NODE_ENV === 'production' ? 'error' : 'off'
}
}
ctrl + s保存代码后,便会⾃动修复格式不正确的代码