vscode 使用ESLint 自動檢查,保存時自動格式化

1:全局安裝eslintjavascript

`npm install -g eslint`
2: 打開vscode 點擊 「文件」-----》「首選項」----》「設置」,在右側「用戶設置/settings.json」里加入一下配置:css

```
{
//eslint 代碼自動檢查相關配置

"eslint.enable": true,
"eslint.autoFixOnSave": true,
"eslint.run": "onType",
"eslint.options": {
"extensions": [".js",".vue"]
},
"eslint.validate": [
"javascriptreact",
"vue",
"javascript", {
"language": "vue",
"autoFix": true
},
"html", {
"language": "html",
"autoFix": true
}
],
}
```
## 下面是個人配置:html

```
{
"team.showWelcomeMessage": false,
"window.zoomLevel": 1,
//eslint 代碼自動檢查相關配置
"eslint.enable": true,
"eslint.autoFixOnSave": true,
"eslint.run": "onType",
"eslint.options": {
"extensions": [".js",".vue"]
},
"eslint.validate": [
"javascriptreact",
"vue",
"javascript", {
"language": "vue",
"autoFix": true
},
"html", {
"language": "html",
"autoFix": true
}
],
"explorer.confirmDelete": false,
"files.associations": {
"*.cjson": "jsonc",
"*.wxss": "css",
"*.wxs": "javascript"
},
"emmet.includeLanguages": {
"wxml": "html"
},
"minapp-vscode.disableAutoConfig": true,
"window.menuBarVisibility": "visible",
"git.enableSmartCommit": true,
"git.autofetch": true,
"liveServer.settings.donotShowInfoMsg": true,
"[html]": {
"editor.defaultFormatter": "vscode.html-language-features"
},
"javascript.updateImportsOnFileMove.enabled": "always",
"workbench.iconTheme": "material-icon-theme",
"workbench.colorTheme": "SynthWave '84",
"editor.fontSize": 16,
"search.followSymlinks": false,
"workbench.sideBar.location": "right",
"vscode_custom_css.policy": true,
"vscode_custom_css.imports":[
"file:///C:/Users/wongseedling/Desktop/vscode-transparent-glow/synthwave84.css",
"file:///C:/Users/wongseedling/Desktop/vscode-transparent-glow/toolbar.css",
"file:///C:/Users/wongseedling/Desktop/vscode-transparent-glow/vscode-vibrancy-style.css",
"file:///C:/Users/wongseedling/Desktop/vscode-transparent-glow/enable-electron-vibrancy.js",
],
"zenMode.restore": true,
"glassit.alpha": 220,
"breadcrumbs.enabled": true,
"terminal.integrated.shell.windows": "C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"
}
```
# 以上能夠安裝eslint 插件加上面配置便可,有興趣的話你能夠往下面看
# 「編碼一時爽,重構火葬場。」
實踐
如何上手?首先仍是官方文檔。我以爲不管是學什麼,你得先去了解它是什麼,以及它爲何出現,而後纔是衡量是否要在工做或生活中使用它。前端

官方文檔:https://eslint.org/vue

中文文檔:https://cn.eslint.org/
ESLint它很靈活,全部的檢查都是基於規則的。java

ESLint規則:https://cn.eslint.org/docs/rules/node

使用ESLint三部曲
安裝
npm install -g eslint
初始化
npm init
編寫配置文件(因爲ESLint配置文件支持多種文件擴展,此處以.eslintrc.js爲例)react

```
module.exports = {
/**
* 默認狀況下,ESLint會在全部父級目錄裏尋找配置文件,一直到根目錄。
* 爲了將ESLint限制在一個特定的項目,設置root: true;
* ESLint一旦發現配置文件中有 root: true,就會中止在父級目錄中尋找。
*/
root: true,
// 指定解析器
// babel-ESLint: 一個對Babel解析器的包裝,使其可以與ESLint兼容。
// parser: 'babel-eslint',
// 設置解析器能幫助ESLint肯定什麼是解析錯誤。
parserOptions: {
parser: 'babel-eslint',
// 指定js版本。語法上的支持
ecmaVersion: 6
},
// 腳本在執行期間訪問的額外的全局變量
// globals: {},
// env: 指定腳本的運行環境
env: {
// 一個環境定義了一組預約義的全局變量。
browser: true,
// 會自動開啓es6語法支持。
es6: true,
node: true
},
// 使用第三方插件。全局安裝的 ESLint 實例只能使用全局安裝的ESLint插件。本地同理,不支持混用。
plugins: [
'html',
'vue'
],
// 配置文件從基礎配置中繼承已啓用的規則。
/**
* eslint:recommended 啓用核心規則,在規則頁面中被標記爲 √ 的。
*/
extends: [
// plugin:(此處不能有空格)包名/配置名稱。解析時plugin是解析成 eslint-plugin-vue。若是有空格會解析失敗,eslint-plugin- vue。
// plugin能夠省略包名的前綴 eslint-plugin-
// 'plugin:vue/essential',
// '@vue/standard',
'eslint:recommended'
// 也能夠指定另外一個基本配置文件的絕對路徑或相對路徑
],


/**
* 每一個規則有【3】個錯誤級別。
* off或0: 關閉該規則;
* warn或1: 開啓規則,使用警告級別的錯誤,不會致使程序退出;
* error或2: 開啓規則,使用錯誤級別的錯誤,當被觸發的時候,程序會退出。
*/
rules: {
/**
* 【================================================ Possible Errors ================================================】
* 這些規則與JavaScript代碼中可能的錯誤或邏輯錯誤有關。
*/
// 強制"for"循環中更新子句的計算器朝着正確的方向移動
'for-direction': 2,
// 禁止function定義中出現重名參數
'no-dupe-args': 2,
// 禁止對象字面量中出現重複的key
'no-dupe-keys': 2,
// 禁止出現重複的case標籤
'no-duplicate-case': 2,
// 禁止對catch子句的參數從新賦值
'no-ex-assign': 2,
// 禁止對關係運算符的左操做數使用否認操做符
'no-unsafe-negation': 2,
// 禁止出現使人困惑的多行表達式
'no-unexpected-multiline': 2,
// 禁止在return、throw、continue、break語句以後出現不可達代碼
'no-unreachable': 2,
// 禁止在finally語句塊中出現控制流語句
'no-unsafe-finally': 2,
// 要求使用isNaN()檢查NaN
'use-isnan': 2,
// 強制typeof表達式與有效的字符串進行比較
'valid-typeof': 2,
// 還能夠寫表達式,厲害了~
'no-debugger': process.env.NODE_ENV === 'production' ? 'error': 'off',
'no-console': process.env.NODE_ENV === 'production' ? 'error': 'off',

/**
* 【================================================ Best Practices ================================================】
* 這些規則是關於最佳實踐的,幫助你避免一些問題。
*/
// 強制 getter 和 setter在對象中成對出現
'accessor-pairs': 2,
// 強制全部控制語句使用一致的括號風格
'curly': [2, 'multi-line'],
// 強制在點號以前和以後一致的換行
'dot-location': [2, 'property'],
// 要求使用 ===和 !==
'eqeqeq': [2, 'allow-null'],
// 禁用arguments.caller 或 arguments.callee
'no-caller': 2,
// 禁止使用空解構模式
'no-empty-pattern': 2,
// 禁止eval()
'no-eval': 2,
// 禁止使用相似eval()的方法
'no-implied-eval': 2,
// 禁止擴展原生類型
'no-extend-native': 2,
// 禁止沒必要要的.bind()調用
'no-extra-bind': 2,
// 禁止case語句落空
'no-fallthrough': 2,
// 禁止數字字面量中使用前導和末尾小數點
'no-floating-decimal': 2,
// 禁用__iterator__屬性
'no-iterator': 2,
// 禁用標籤語句
'no-labels': [2, {
'allowLoop' : false,
'allowSwitch': false
}],
// 禁用沒必要要嵌套塊
'no-lone-blocks': 2,
// 禁止使用多個空格
'no-multi-spaces': 2,
// 禁止使用多行字符串
'no-multi-str': 2,
// 禁止對String,Number 和 Boolean 使用new操做符
'no-new-wrappers': 2,
// 禁用八進制字面量
'no-octal': 2,
// 禁止在字符串中使用八進制轉義序列
'no-octal-escape': 2,
// 禁止使用__proto__屬性
'no-proto': 2,
// 禁止屢次聲明同一變量
'no-redeclare': 2,
// 禁止在return語句中使用賦值語句
'no-return-assign': [2, 'except-parens'],
// 禁止自我賦值
'no-self-assign': 2,
// 禁止自我比較
'no-self-compare': 2,
// 禁用逗號操做符
'no-sequences': 2,
// 禁止拋出異常字面量
'no-throw-literal': 2,
// 禁止一成不變的循環條件
'no-unmodified-loop-condition': 2,
// 禁止沒必要要的.call()和.apply()
'no-useless-call': 2,
// 禁止沒必要要的轉義字符
'no-useless-escape': 2,
// 禁用with語句
'no-with': 2,
// 要求IIFE使用括號括起來
'wrap-iife': 2,
// 要求或禁止Yoda條件。 if("red" === color) { //字面量在前,變量在後 }
'yoda': [2, 'never'], // 比較毫不能是Yoda條件(須要變量在前,字面量在後)

/**
* 【================================================ ECMAScript 6 ================================================】
* 這些規則只與ES6有關,即一般所說的ES2015。
*/
// 強制箭頭函數先後使用一致的空格
'arrow-spacing': [2, {
'before': true,
'after' : true
}],
// 要求在構造函數中有super()調用
'constructor-super': 2,
// 強制generator函數中*號周圍使用一致的空格
'generator-star-spacing': [2, {
'before': true,
'after' : true
}],
// 禁止修改類聲明的變量
'no-class-assign': 2,
// 禁止修改const聲明的變量
'no-const-assign': 2,
// 禁止類成員中出現重複的名稱
'no-dupe-class-members': 2,
// 禁止 Symbolnew 操做符和 new 一塊兒使用
'no-new-symbol': 2,
// 禁止在構造函數中,在調用super()以前使用 this 或 super
'no-this-before-super': 2,
// 禁止在對象中使用沒必要要的計算屬性
'no-useless-computed-key': 2,
// 禁止沒必要要的構造函數
'no-useless-constructor': 2,
// 禁止模板字符串中嵌入表達式周圍空格的使用
'template-curly-spacing': [2, 'never'],
// 強制yield*表達式中的*周圍使用空格
'yield-star-spacing': [2, 'both'],
// 要求使用const聲明那些聲明後再也不被修改的變量
'prefer-const': 2,

/**
* 【================================================ Stylistic Issues ================================================】
* 這些規則是關於代碼風格的。
*/
// 獲取當前執行環境的上下文時,強制使用一致的命名(此處強制使用 'that')。
'consistent-this': [2, 'that'],
// 禁止或強制在代碼塊中開括號前和閉括號後有空格 { return 11 }
'block-spacing': [2, 'always'],
// 強制在代碼塊中使用一致的大括號風格
'brace-style': [2, '1tbs', {
'allowSingleLine': true
}],
// 強制使用駝峯拼寫法命名規定
'camelcase': [0, {
'properties': 'always'
}],
// 要求或禁止末尾逗號
'comma-dangle': [2, 'never'],
// 強制在逗號先後使用一致的空格
'comma-spacing': [2, {
'before': false,
'after' : true
}],
// 強制在逗號先後使用一致的空格
'comma-style': [2, 'last'],
// 要求或禁止文件末尾存在空行
'eol-last': 2,
// 強制使用一致的縮進
'indent': [2, 2, {
'SwitchCase': 1
}],
// 強制在JSX屬性中一致地使用雙引號或單引號
'jsx-quotes': [2, 'prefer-single'],
// 要求構造函數首字母大寫
'new-cap': [2, {
'newIsCap': true,
'capIsNew': false
}],
// 要求構造無參構造函數時有圓括號
'new-parens': 2,
// 禁用Array構造函數
'no-array-constructor': 2,
// 禁止空格和tab的混合縮進
'no-mixed-spaces-and-tabs': 2,
// 禁止出現多行空行
'no-multiple-empty-lines': [2, {
// 最大連續空行數
max: 2
}],
// 禁止在函數標識符和其調用之間有空格
'func-call-spacing': 2,
// 禁止行尾空格
'no-trailing-spaces': 2,
// 禁止能夠在有更簡單的可替代的表達式時使用三元操做符
'no-unneeded-ternary': [2, {
// 容許表達式做爲默認的賦值模式
'defaultAssignment': true
}],
// 禁止屬性前有空白
'no-whitespace-before-property': 2,
// 強制函數中的變量要麼一塊兒聲明要麼分開聲明
'one-var': [2, {
'initialized': 'never'
}],
// 強制操做符使用一致的換行符
'operator-linebreak': [2, 'after', {
'overrides': {
'?': 'before',
':': 'before'
}
}],
// 要求或禁止塊內填充
'padded-blocks': [2, 'never'],
// 強烈使用一致的反勾號``、雙引號""或單引號''
'quotes': [2, 'single', {
// 容許字符串使用單引號或者雙引號,只要字符串中包含了一個其餘引號,不然須要轉義
'avoidEscape': true,
// 容許字符串使用反勾號
'allowTemplateLiterals': true
}],
// 禁止使用分號代替ASI(自動分號插入)
'semi': [2, 'never'],
// 強制分號以前和以後使用一致的空格
'semi-spacing': [2, {
'before': false,
'after' : true
}],
// 強制在塊以前使用一致的空格
'space-before-blocks': [2, 'always'],
// 強制在圓括號內使用一致的空格
'space-in-parens': [2, 'never'],
// 要求操做符周圍有空格
'space-infix-ops': 2,
// 強制在一元操做符先後使用一致的空格
'space-unary-ops': [2, {
'words' : true,
'nonwords': false
}],
// 強制在註釋// 或/*使用一致的空格
'spaced-comment': [1, 'always', {
'markers': ['global', 'globals', 'eslint', 'eslint-disable', '*package', '!', ',']
}],
// 強制在大括號中使用一致的空格
'object-curly-spacing': [2, 'always', {
'objectsInObjects': false
}],
// 禁止或強制在括號內使用空格
'array-bracket-spacing': [2, 'never'],
// 強制要求在對象字面量的屬性中鍵和值之間使用一致的間距
'key-spacing': [2, {
'beforeColon': false,
'afterColon' : true
}],

/**
* 【================================================ Node.js and CommonJS ================================================】
* 這些規則是關於Node.js 或 在瀏覽器中使用CommonJS的。
*/
// 要求回調函數中有容錯處理
'handle-callback-err': [2, '^(err|error)$'],
// 禁止調用 require 時使用new操做符
'no-new-require': 2,
// 禁止對__dirname和__filename進行字符串鏈接
'no-path-concat': 1,
// 強制在function的左括號以前使用一致的空格
'space-before-function-paren': [2, 'never'],

/**
* 【================================================ Possible Errors ================================================】
* 這些規則與JavaScript代碼中可能的錯誤或邏輯錯誤有關。
*/
// 禁止條件表達式中出現賦值操做符
'no-cond-assign': 2,
// 禁止在正則表達式中使用控制字符
'no-control-regex': 0,
// 禁止在正則表達式中使用空字符集
'no-empty-character-class': 2,
// 禁止沒必要要的布爾轉換
'no-extra-boolean-cast': 2,
// 禁止沒必要要的括號
'no-extra-parens': [2, 'functions'],
// 禁止對function聲明從新賦值
'no-func-assign': 2,
// 禁止在嵌套塊中出現變量聲明或function聲明
'no-inner-declarations': [2, 'functions'],
// 禁止RegExp構造函數中存在無效的正則表達式字符串
'no-invalid-regexp': 2,
// 禁止在字符串和註釋以外不規則的空白
'no-irregular-whitespace': 2,
// 禁止把全局對象做爲函數調用
'no-obj-calls': 2,
// 禁止正則表達式字面量中出現多個空格
'no-regex-spaces': 2,
// 禁用稀疏數組
'no-sparse-arrays': 2,

/**
* 【================================================ Variables ================================================】
* 這些規則與變量聲明有關。
*/
// 禁止刪除變量
'no-delete-var': 2,
// 不容許標籤與變量同名
'no-label-var': 2,
// 禁止將標識符定義爲受限的名字
'no-shadow-restricted-names': 2,
// 禁止未聲明的變量,除非它們在/*global */註釋中被提到
'no-undef': 2,
// 禁止將變量初始化爲undefined
'no-undef-init': 2,
// 禁止出現未使用的變量
'no-unused-vars': [2, {
'var' : 'all',
'args': 'none'
}],

/**
* 【================================================ 配置定義在插件中的規則 ================================================】
* 格式: 插件名/規則ID
*/
//
'vue/no-parsing-error': [2, { 'x-invalid-end-tag': false }]
}
}
```
.eslintignore:能夠配置指定的目錄或文件不進行ESLint檢查。
這個項目框架是iview-admin2.x.x的,項目自己基於vue 3.x以及webpack4.x,項目自身作了基本配置。webpack

還要安裝咱們的插件,git

npm install eslint-plugin-html --save-dev
npm install eslint-plugin-vue --save-dev

在VS Code中自動按照ESLint規則格式化代碼
在VS Code中安裝插件(ESLint、Vurter、Prettier)
文件 => 首選項 => 設置打開settings.json文件,我的配置以下
---------------------

```
{
// 是否容許自定義的snippet片斷提示
"editor.snippetSuggestions" : "top",
"editor.fontSize" : 20,
"editor.fontWeight" : "400",
"editor.formatOnType" : true,
"workbench.iconTheme" : "material-icon-theme",
"workbench.colorTheme" : "One Dark Pro",
"guides.enabled": false,
"editor.tabSize": 2,
"git.confirmSync": false,
"window.zoomLevel": 0,
"editor.renderWhitespace": "boundary",
"editor.cursorBlinking": "smooth",
"editor.minimap.enabled": true,
"editor.minimap.renderCharacters": false,
"window.title": "${dirty}${activeEditorMedium}${separator}${rootName}",
"editor.codeLens": true,
// 配置文件關聯,以便啓用對應的提示
"files.associations": {
"*.vue": "vue",
"*.wxss": "css"
},
// 配置emmet是否啓用tab展開縮寫
"emmet.triggerExpansionOnTab": true,
// 配置emmet對文件類型的支持
"emmet.syntaxProfiles": {
"javascript": "jsx",
"vue": "html",
"vue-html": "html"
},
// 是否開啓eslint檢測
"eslint.enable": true,
// 文件保存時是否根據eslint進行格式化
"eslint.autoFixOnSave": true,
// eslint配置文件
"eslint.options": {
"extensions": [
".js",
".vue"
]
},
// eslint可以識別的文件後綴類型
"eslint.validate": [
"javascript",{
"language": "vue",
"autoFix": true
},"html",
"vue"
],
"search.exclude": {
"**/node_modules": true,
"**/bower_components": true,
"**/dist": true
},
// 格式化快捷鍵(默認):Shift+Alt+F
// prettier進行格式化時,開啓eslint支持
// "prettier.eslintIntegration": true,
// 是否使用單引號
"prettier.singleQuote": true,
}
```
總結
遇到的問題:

未安裝插件(要注意觀看官網的使用規則)eslint-plugin-html和eslint-plugin-vue報錯;parser的配置問題:https://github.com/vuejs/eslint-plugin-vue/issues/30前端架構師大佬QQ羣:634196762 私人羣不打廣告 只討論技術# 我的小程序 你們能夠關注下 ![在這裏插入圖片描述](https://img-blog.csdnimg.cn/2019052122013457.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80Mzc2NDgxNA==,size_16,color_FFFFFF,t_70)

相關文章
相關標籤/搜索