Eslint的目標是提供一個插件化的javascript代碼檢測工具。使用腳手架搭建的JS項目通常會帶有Eslint,而普通的JS項目都是手動創建目錄結構、文件,代碼規范常常靠團隊習慣約定,這樣約束性不強,很不利於合作開發。
現提供一種結合VSCode的Eslint規范方法。
1.安裝依賴
項目目錄中安裝eslint和standard(是一種代碼風格,和vue類型項目默認的一致,也有其他風格可選)
cmd到項目根目錄,運行以下命令:
1 npm i eslint standard --save-dev
2.配置eslint
在項目根目錄下添加 .eslintrc.js 文件
1 module.exports = { 2 root: true, 3 env: { 4 browser: true, 5 es6: true, 6 }, 7 extends: [ 8 'standard', 9 ], 10 globals: { 11 Atomics: 'readonly', 12 SharedArrayBuffer: 'readonly', 13 }, 14 parserOptions: { 15 ecmaVersion: 2018, 16 sourceType: 'module', 17 }, 18 rules: { 19 } 20 };
這里使用了standard的規則,如果使用過程中有規則不符合要求,可自行在rules項中進行配置,可配置的內容如下:

1 // 0是off關閉,1是warning警告,2是error報錯 2 rules: { 3 // "no-alert": 1,//禁止使用alert confirm prompt 4 // "no-array-constructor": 2,//禁止使用數組構造器 5 // "no-bitwise": 0,//禁止使用按位運算符 6 // "no-caller": 1,//禁止使用arguments.caller或arguments.callee 7 // "no-catch-shadow": 2,//禁止catch子句參數與外部作用域變量同名 8 // "no-class-assign": 2,//禁止給類賦值 9 // "no-cond-assign": 2,//禁止在條件表達式中使用賦值語句 10 // "no-console": 1,//禁止使用console 11 // "no-const-assign": 2,//禁止修改const聲明的變量 12 // "no-constant-condition": 2,//禁止在條件中使用常量表達式 if(true) if(1) 13 // "no-continue": 0,//禁止使用continue 14 // "no-control-regex": 2,//禁止在正則表達式中使用控制字符 15 // "no-debugger": 2,//禁止使用debugger 16 // "no-delete-var": 2,//不能對var聲明的變量使用delete操作符 17 // "no-div-regex": 1,//不能使用看起來像除法的正則表達式/=foo/ 18 // "no-dupe-keys": 2,//在創建對象字面量時不允許鍵重復 {a:1,a:1} 19 // "no-dupe-args": 2,//函數參數不能重復 20 // "no-duplicate-case": 2,//switch中的case標簽不能重復 21 // "no-else-return": 2,//如果if語句里面有return,后面不能跟else語句 22 // "no-empty": 2,//塊語句中的內容不能為空 23 // "no-empty-character-class": 2,//正則表達式中的[]內容不能為空 24 // "no-empty-label": 2,//禁止使用空label 25 // "no-eq-null": 2,//禁止對null使用==或!=運算符 26 // "no-eval": 1,//禁止使用eval 27 // "no-ex-assign": 2,//禁止給catch語句中的異常參數賦值 28 // "no-extend-native": 2,//禁止擴展native對象 29 // "no-extra-bind": 2,//禁止不必要的函數綁定 30 // "no-extra-boolean-cast": 2,//禁止不必要的bool轉換 31 // "no-extra-parens": 2,//禁止非必要的括號 32 // "no-extra-semi": 2,//禁止多余的冒號 33 // "no-fallthrough": 1,//禁止switch穿透 34 // "no-floating-decimal": 2,//禁止省略浮點數中的0 .5 3. 35 // "no-func-assign": 2,//禁止重復的函數聲明 36 // "no-implicit-coercion": 1,//禁止隱式轉換 37 // "no-implied-eval": 2,//禁止使用隱式eval 38 // "no-inline-comments": 0,//禁止行內備注 39 // "no-inner-declarations": [2, "functions"],//禁止在塊語句中使用聲明(變量或函數) 40 // "no-invalid-regexp": 2,//禁止無效的正則表達式 41 // "no-invalid-this": 2,//禁止無效的this,只能用在構造器,類,對象字面量 42 // "no-irregular-whitespace": 2,//不能有不規則的空格 43 // "no-iterator": 2,//禁止使用__iterator__ 屬性 44 // "no-label-var": 2,//label名不能與var聲明的變量名相同 45 // "no-labels": 2,//禁止標簽聲明 46 // "no-lone-blocks": 2,//禁止不必要的嵌套塊 47 // "no-lonely-if": 2,//禁止else語句內只有if語句 48 // "no-loop-func": 1,//禁止在循環中使用函數(如果沒有引用外部變量不形成閉包就可以) 49 // "no-mixed-requires": [0, false],//聲明時不能混用聲明類型 50 // "no-mixed-spaces-and-tabs": [2, false],//禁止混用tab和空格 51 // "linebreak-style": [0, "windows"],//換行風格 52 // "no-multi-spaces": 1,//不能用多余的空格 53 // "no-multi-str": 2,//字符串不能用\換行 54 // "no-multiple-empty-lines": [1, {"max": 2}],//空行最多不能超過2行 55 // "no-native-reassign": 2,//不能重寫native對象 56 // "no-negated-in-lhs": 2,//in 操作符的左邊不能有! 57 // "no-nested-ternary": 0,//禁止使用嵌套的三目運算 58 // "no-new": 1,//禁止在使用new構造一個實例后不賦值 59 // "no-new-func": 1,//禁止使用new Function 60 // "no-new-object": 2,//禁止使用new Object() 61 // "no-new-require": 2,//禁止使用new require 62 // "no-new-wrappers": 2,//禁止使用new創建包裝實例,new String new Boolean new Number 63 // "no-obj-calls": 2,//不能調用內置的全局對象,比如Math() JSON() 64 // "no-octal": 2,//禁止使用八進制數字 65 // "no-octal-escape": 2,//禁止使用八進制轉義序列 66 // "no-param-reassign": 2,//禁止給參數重新賦值 67 // "no-path-concat": 0,//node中不能使用__dirname或__filename做路徑拼接 68 // "no-plusplus": 0,//禁止使用++,-- 69 // "no-process-env": 0,//禁止使用process.env 70 // "no-process-exit": 0,//禁止使用process.exit() 71 // "no-proto": 2,//禁止使用__proto__屬性 72 // "no-redeclare": 2,//禁止重復聲明變量 73 // "no-regex-spaces": 2,//禁止在正則表達式字面量中使用多個空格 /foo bar/ 74 // "no-restricted-modules": 0,//如果禁用了指定模塊,使用就會報錯 75 // "no-return-assign": 1,//return 語句中不能有賦值表達式 76 // "no-script-url": 0,//禁止使用javascript:void(0) 77 // "no-self-compare": 2,//不能比較自身 78 // "no-sequences": 0,//禁止使用逗號運算符 79 // "no-shadow": 2,//外部作用域中的變量不能與它所包含的作用域中的變量或參數同名 80 // "no-shadow-restricted-names": 2,//嚴格模式中規定的限制標識符不能作為聲明時的變量名使用 81 // "no-spaced-func": 2,//函數調用時 函數名與()之間不能有空格 82 // "no-sparse-arrays": 2,//禁止稀疏數組, [1,,2] 83 // "no-sync": 0,//nodejs 禁止同步方法 84 // "no-ternary": 0,//禁止使用三目運算符 85 // "no-trailing-spaces": 1,//一行結束后面不要有空格 86 // "no-this-before-super": 0,//在調用super()之前不能使用this或super 87 // "no-throw-literal": 2,//禁止拋出字面量錯誤 throw "error"; 88 // "no-undef": 1,//不能有未定義的變量 89 // "no-undef-init": 2,//變量初始化時不能直接給它賦值為undefined 90 // "no-undefined": 2,//不能使用undefined 91 // "no-unexpected-multiline": 2,//避免多行表達式 92 // "no-underscore-dangle": 1,//標識符不能以_開頭或結尾 93 // "no-unneeded-ternary": 2,//禁止不必要的嵌套 var isYes = answer === 1 ? true : false; 94 // "no-unreachable": 2,//不能有無法執行的代碼 95 // "no-unused-expressions": 2,//禁止無用的表達式 96 // "no-unused-vars": [2, {"vars": "all", "args": "after-used"}],//不能有聲明后未被使用的變量或參數 97 // "no-use-before-define": 2,//未定義前不能使用 98 // "no-useless-call": 2,//禁止不必要的call和apply 99 // "no-void": 2,//禁用void操作符 100 // "no-var": 0,//禁用var,用let和const代替 101 // "no-warning-comments": [1, { "terms": ["todo", "fixme", "xxx"], "location": "start" }],//不能有警告備注 102 // "no-with": 2,//禁用with 103 // "array-bracket-spacing": [2, "never"],//是否允許非空數組里面有多余的空格 104 // "arrow-parens": 0,//箭頭函數用小括號括起來 105 // "arrow-spacing": 0,//=>的前/后括號 106 // "accessor-pairs": 0,//在對象中使用getter/setter 107 // "block-scoped-var": 0,//塊語句中使用var 108 // "brace-style": [1, "1tbs"],//大括號風格 109 // "callback-return": 1,//避免多次調用回調什么的 110 // "camelcase": 2,//強制駝峰法命名 111 // "comma-dangle": [2, "never"],//對象字面量項尾不能有逗號 112 // "comma-spacing": 0,//逗號前后的空格 113 // "comma-style": [2, "last"],//逗號風格,換行時在行首還是行尾 114 // "complexity": [0, 11],//循環復雜度 115 // "computed-property-spacing": [0, "never"],//是否允許計算后的鍵名什么的 116 // "consistent-return": 0,//return 后面是否允許省略 117 // "consistent-this": [2, "that"],//this別名 118 // "constructor-super": 0,//非派生類不能調用super,派生類必須調用super 119 // "curly": [2, "all"],//必須使用 if(){} 中的{} 120 // "default-case": 2,//switch語句最后必須有default 121 // "dot-location": 0,//對象訪問符的位置,換行的時候在行首還是行尾 122 // "dot-notation": [0, { "allowKeywords": true }],//避免不必要的方括號 123 // "eol-last": 0,//文件以單一的換行符結束 124 // "eqeqeq": 2,//必須使用全等 125 // "func-names": 0,//函數表達式必須有名字 126 // "func-style": [0, "declaration"],//函數風格,規定只能使用函數聲明/函數表達式 127 // "generator-star-spacing": 0,//生成器函數*的前后空格 128 // "guard-for-in": 0,//for in循環要用if語句過濾 129 // "handle-callback-err": 0,//nodejs 處理錯誤 130 // "id-length": 0,//變量名長度 131 // "indent": [2, 2],//縮進風格 132 // "init-declarations": 0,//聲明時必須賦初值 133 // "key-spacing": [0, { "beforeColon": false, "afterColon": true }],//對象字面量中冒號的前后空格 134 // "lines-around-comment": 0,//行前/行后備注 135 // "max-depth": [0, 4],//嵌套塊深度 136 // "max-len": [0, 80, 4],//字符串最大長度 137 // "max-nested-callbacks": [0, 2],//回調嵌套深度 138 // "max-params": [0, 3],//函數最多只能有3個參數 139 // "max-statements": [0, 10],//函數內最多有幾個聲明 140 // "new-cap": 2,//函數名首行大寫必須使用new方式調用,首行小寫必須用不帶new方式調用 141 // "new-parens": 2,//new時必須加小括號 142 // "newline-after-var": 0,//變量聲明后是否需要空一行 143 // "object-curly-spacing": [0, "never"],//大括號內是否允許不必要的空格 144 // "object-shorthand": 0,//強制對象字面量縮寫語法 145 // "one-var": 1,//連續聲明 146 // "operator-assignment": [0, "always"],//賦值運算符 += -=什么的 147 // "operator-linebreak": [2, "after"],//換行時運算符在行尾還是行首 148 // "padded-blocks": 0,//塊語句內行首行尾是否要空行 149 // "prefer-const": 0,//首選const 150 // "prefer-spread": 0,//首選展開運算 151 // "prefer-reflect": 0,//首選Reflect的方法 152 // "quotes": [1, "single"],//引號類型 `` "" '' 153 // "quote-props":[2, "always"],//對象字面量中的屬性名是否強制雙引號 154 // "radix": 2,//parseInt必須指定第二個參數 155 // "id-match": 0,//命名檢測 156 // "require-yield": 0,//生成器函數必須有yield 157 // "semi": [2, "never"],//語句強制分號結尾 158 // "semi-spacing": [0, {"before": false, "after": true}],//分號前后空格 159 // "sort-vars": 0,//變量聲明時排序 160 // "space-after-keywords": [0, "always"],//關鍵字后面是否要空一格 161 // "space-before-blocks": [0, "always"],//不以新行開始的塊{前面要不要有空格 162 // "space-before-function-paren": [0, "always"],//函數定義時括號前面要不要有空格 163 // "space-in-parens": [0, "never"],//小括號里面要不要有空格 164 // "space-infix-ops": 0,//中綴操作符周圍要不要有空格 165 // "space-return-throw-case": 2,//return throw case后面要不要加空格 166 // "space-unary-ops": [0, { "words": true, "nonwords": false }],//一元運算符的前/后要不要加空格 167 // "spaced-comment": 0,//注釋風格要不要有空格什么的 168 // "strict": 2,//使用嚴格模式 169 // "use-isnan": 2,//禁止比較時使用NaN,只能用isNaN() 170 // "valid-jsdoc": 0,//jsdoc規則 171 // "valid-typeof": 2,//必須使用合法的typeof的值 172 // "vars-on-top": 2,//var必須放在作用域頂部 173 // "wrap-iife": [2, "inside"],//立即執行函數表達式的小括號風格 174 // "wrap-regex": 0,//正則表達式字面量用小括號包起來 175 // "yoda": [2, "never"]//禁止尤達條件 176 }
3.VSCode設置
3.1安裝Eslint插件,可能需要重啟
3.2安裝后打開項目中的代碼,可以看到對於不符合規范的已經給出了顯示
把鼠標放上去之后也會有相應的提示
點擊ctrl + . 會提示修復錯誤
3.3自動修復錯誤
每次手動修復錯誤太麻煩了,可以設置VSCode在保存時自動修復eslint的錯誤:
在settings.json中添加:
1 "editor.codeActionsOnSave": { 2 "source.fixAll.eslint": true 3 }, 4 "eslint.format.enable": true,
如果有沖突請把VSCode的自動格式化設為false或注釋掉:
1 // "editor.formatOnPaste": true, 2 // "editor.formatOnSave": true, 3 // "editor.formatOnType": true, // 自動化的格式和eslint不一致,使用eslint時需要關閉,其他情況下應該開啟方便格式化代碼
4.忽略檢查
默認會對所有文件進行檢查,包括一些引入的包:
實際上,我們不希望對這些做檢查,可以添加 .eslintignore文件,配置需要忽略的目錄,如下:
1 /lib/ 2 /libs/ 3 /build/ 4 /config/ 5 /dist/ 6 # /*.js 7 /test/unit/coverage/
以上,記錄了在普通項目中添加eslint的步驟,有不詳之處,歡迎留言交流~~