vscode中配置步驟
- vs code中安裝ESLint擴展;
- 全局或者局部安裝eslint庫,因為vs code的ESLint的擴展運行需要ESlint庫。vscode首先從當前打開的工作去文件夾中查找,如果找不到,則在全局環境中查找;
//全局安裝 npm install eslint -g //當前項目中安裝 npm install eslint --save-dev
- 安裝完成之后,在vscode的file->preferences->setting中搜索eslint,會打開有關該擴展的一些設置,根據需要選擇。通過ESLint擴展右下角的設置選擇configure extension settings同樣可以達到設置界面。
- 完成以上三步,vscode中就已經可以完成基本的代碼檢查功能,如果沒有進一步需求,可以不用繼續向下看了。eslint的運行包含Javascript生態系統一直以來總結的檢查規則,用戶或者團隊如果想要指定添加自己的規則,需要添加.eslintrc.js/.eslintrc.json有關於eslint的配置文件。改文件可以通過命令生成,當然也可以自己直接添加。運行命令之后會有一系列提示和選擇,可以根據需要選擇,也可以直接ENTER,然后在生成的文件中自己編寫。
//全局安裝下,自動生成配置文件 eslint --init //使用當前工作區安裝的eslint,生成配置文件 ./node_modules/.bin/eslint --init
- 添加.eslintrc.js文件到vscode中,在第三步中的settings設置中,會找到Eslint:options設置,在該參數中的設置.eslintrc.js的路徑。
{ "eslint.options": { "configFile": "C:/mydirectory/.eslintrc.json" } }
- 最后來了解一下.eslintrc.js文件的配置,詳細信息請查看官網:
// .eslintrc.js module.exports = { // 指定解析器 'parser': '', // 指定解析器選項 'parserOptions': {}, // 指定腳本的運行環境 'env': {}, // 別人可以直接使用你配置好的ESLint 'root': true, // 腳本在執行期間訪問的額外的全局變量 'globals': {}, // 啟用的規則及其各自的錯誤級別 'rules': {} };
- 借來的具體實際項目配置,雖然比較復雜,但是如果是團隊開發,詳細一些有利於將來的維護。今飛凱達
// .eslintrc.js module.exports = { // 解析ES6 'parser': 'babel-eslint', 'parserOptions': { // 啟用ES8語法支持 'ecmaVersion': 2017, // module表示ECMAScript模塊 'sourceType': 'module', // 使用額外的語言特性 'ecmaFeatures': { 'experimentalObjectRestSpread': true, 'jsx': true, 'modules': true, } }, // 這些環境並不是互斥的,所以你可以同時定義多個 'env': { 'browser': true, 'jquery': true, 'node': true, 'commonjs': true, 'es6': true, }, 'root': true, // 當訪問當前源文件內未定義的變量時,no-undef 規則將發出警告 // 所以需要定義這些額外的全局變量 'globals': { 'OnlySVG': true, 'monitor': true, 'CanvasRender': true, 'Vue': true, 'VueRouter': true }, 'rules': { // 設置了 setter ,必須相應設置 getter ,反之不必須 'accessor-pairs': 2, // 數組方括號前后的換行符使用規則 // @off 不關心 'array-bracket-newline': 0, // 數組方括號前后的空格使用規則 // @off 不關心 'array-bracket-spacing': 0, // 數組的 map、filter、sort 等方法,回調函數必須有返回值 'array-callback-return': 2, // 每個數組項是否獨占一行 // @off 不關心 'array-element-newline': 0, // 箭頭函數的書寫規則 // @off 不限制 'arrow-body-style': 0, // 箭頭函數的圓括號使用規則 // @off 不限制 'arrow-parens': 0, // 箭頭函數的空格使用規則 // @off 不限制 'arrow-spacing': 0, // 不能在塊外使用塊作用域內 var 定義的變量 'block-scoped-var': 2, // 代碼塊花括號前后的空格規則 // @off 不關心 'block-spacing': 0, // if else 的花括號換行規則 // @off 不關心 'brace-style': 0, // callback 之后必須立即 return // @off 沒必要 'callback-return': 0, // 變量名必須使用駝峰式 // @off 暫不限制 'camelcase': 0, // 注釋的首字母應該大寫 // @off 沒必要 'capitalized-comments': 0, // class 的非靜態方法必須包含 this 關鍵字 'class-methods-use-this': 2, // 對象的最后一項后面是否寫逗號 // @off 此項目不關心 // @fixable 對於 PC 項目考慮兼容性時需要設置 'comma-dangle': 0, // 逗號前后是否有空格 // @off 不關心 'comma-spacing': 0, // 逗號寫在行首還是行尾 // @off 不關心 'comma-style': 0, // 禁止函數 if ... else if ... else 的復雜度超過 20 'complexity': 2, // 使用方括號訪問對象屬性時,方括號前后的空格規則 // @off 不關心 'computed-property-spacing': 0, // 禁止函數在不同條件下返回不同類型的值 // @off 有時候會希望通過參數獲取不同類型的返回值 'consistent-return': 0, // this 的別名規則,只允許 self 或 that 'consistent-this': [2, 'self', 'that'], // 構造函數中必須調用 super // @off 沒必要 'constructor-super': 0, // if 后必須包含 { ,單行 if 除外 'curly': [2, 'multi-line', 'consistent'], // switch 語句必須包含 default 'default-case': 2, // 鏈式操作時,點的位置,是在上一行結尾還是下一行開頭 // @off 不關心 'dot-location': 0, // 文件最后必須有空行 // @off 不限制 'eol-last': 0, // 必須使用 === 和 !== ,和 null 對比時除外 'eqeqeq': [2, 'always', { 'null': 'ignore' }], // for 循環不得因方向錯誤造成死循環 'for-direction': 2, // 執行函數的圓括號前后的空格規則 // @off 不關心 'func-call-spacing': 0, // 把函數賦給變量或對象屬性時,函數名和變量名或對象屬性名必須一致 // @off 不限制 'func-name-matching': 0, // 不允許匿名函數 // @off 不限制 'func-names': 0, // 必須只使用函數申明或只使用函數表達式 // @off 不限制 'func-style': 0, // generator 的 * 前后空格使用規則 // @off 不限制 'generator-star-spacing': 0, // getter 必須有返回值,允許返回 undefined 'getter-return': [2, { allowImplicit: true }], // require 必須在全局作用域下 // @off 條件加載很常見 'global-require': 0, // for in 時需檢測 hasOwnProperty 'guard-for-in': 2, // callback 中的 err、error 參數和變量必須被處理 'handle-callback-err': 2, // id 黑名單 // @off 暫時沒有 'id-blacklist': 0, // 變量名長度限制 // @off 長度不是重點,清晰易讀才是關鍵 'id-length': 0, // 限制變量名必須匹配指定的正則表達式 // @off 沒必要限制變量名 'id-match': 0, // 縮進使用 tab 還是空格 // @off 不關心 'indent': 0, // 變量必須在定義的時候賦值 // @off 先定義后賦值很常見 'init-declarations': 0, // jsx 語法中,屬性的值必須使用雙引號 'jsx-quotes': [2, 'prefer-double'], // 對象字面量冒號前后的空格使用規則 // @off 不關心 'key-spacing': 0, // 關鍵字前后必須有空格 'keyword-spacing': 2, // 換行符使用規則 // @off 不關心 'linebreak-style': 0, // 單行注釋必須寫在前一行還是行尾 // @off 不限制 'line-comment-position': 0, // 注釋前后是否要空一行 // @off 不限制 'lines-around-comment': 0, // 最大塊嵌套深度為 5 層 'max-depth': [2, 5], // 限制單行代碼的長度 // @off 不限制 'max-len': 0, // 限制單個文件最大行數 // @off 不限制 'max-lines': 0, // 最大回調深度為 3 層 'max-nested-callbacks': [2, 3], // 函數的形參不能多於8個 'max-params': [2, 8], // 限制一行中的語句數量 // @off 沒必要限制 'max-statements-per-line': 0, // 限制函數塊中的語句數量 // @off 沒必要限制 'max-statements': 0, // 三元表達式的換行規則 // @off 不限制 'multiline-ternary': 0, // new關鍵字后類名應首字母大寫 'new-cap': [2, { 'capIsNew': false, // 允許大寫開頭的函數直接執行 }], // new 關鍵字后類應包含圓括號 'new-parens': 2, // 鏈式調用是否要換行 // @off 不限制 'newline-per-chained-call': 0, // 禁止 alert,提醒開發者,上線時要去掉 'no-alert': 1, // 禁止使用 Array 構造函數,使用 Array(num) 直接創建長度為 num 的數組時可以 'no-array-constructor': 2, // 禁止將 await 寫在循環里 'no-await-in-loop': 2, // 禁止位運算 // @off 不限制 'no-bitwise': 0, // 禁止在 Node.js 中直接調用 Buffer 構造函數 'no-buffer-constructor': 2, // 禁止使用 arguments.caller 和 arguments.callee 'no-caller': 2, // switch的條件中出現 var、let、const、function、class 等關鍵字,必須使用花括號把內容括起來 'no-case-declarations': 2, // catch中不得使用已定義的變量名 'no-catch-shadow': 2, // class定義的類名不得與其它變量重名 'no-class-assign': 2, // 禁止與 -0 做比較 'no-compare-neg-zero': 2, // 禁止在 if、for、while 中出現賦值語句,除非用圓括號括起來 'no-cond-assign': [2, 'except-parens'], // 禁止出現難以理解的箭頭函數,除非用圓括號括起來 'no-confusing-arrow': [2, { 'allowParens': true }], // 禁止使用 console,提醒開發者,上線時要去掉 'no-console': 1, // 禁止使用常量作為判斷條件 'no-constant-condition': [2, { 'checkLoops': false }], // 禁止對 const 定義重新賦值 'no-const-assign': 2, // 禁止 continue // @off 很常用 'no-continue': 0, // 禁止正則表達式中出現 Ctrl 鍵的 ASCII 表示,即/\x1f/ 'no-control-regex': 2, // 禁止 debugger 語句,提醒開發者,上線時要去掉 'no-debugger': 1, // 禁止對變量使用 delete 關鍵字,刪除對象的屬性不受限制 'no-delete-var': 2, // 禁止在正則表達式中出現形似除法操作符的開頭,如 let a = /=foo/ // @off 有代碼高亮的話,在閱讀這種代碼時,也完全不會產生歧義或理解上的困難 'no-div-regex': 0, // 函數參數禁止重名 'no-dupe-args': 2, // 禁止對象出現重名鍵值 'no-dupe-keys': 2, // 類方法禁止重名 'no-dupe-class-members': 2, // 禁止 switch 中出現相同的 case 'no-duplicate-case': 2, // 禁止重復 import 'no-duplicate-imports': 2, // 禁止出現 if (cond) { return a } else { return b },應該寫為 if (cond) { return a } return b // @off 有時前一種寫法更清晰易懂 'no-else-return': 0, // 正則表達式中禁止出現空的字符集[] 'no-empty-character-class': 2, // 禁止空的 function // 包含注釋的情況下允許 'no-empty-function': 2, // 禁止解構中出現空 {} 或 [] 'no-empty-pattern': 2, // 禁止出現空代碼塊 'no-empty': [2, { 'allowEmptyCatch': true }], // 禁止 == 和 != 與 null 做比較,必須用 === 或 !== // @off 非嚴格相等可以同時判斷 null 和 undefined 'no-eq-null': 0, // 禁止使用 eval 'no-eval': 2, // catch 定義的參數禁止賦值 'no-ex-assign': 2, // 禁止擴展原生對象 'no-extend-native': [2, { 'exceptions': ['Array', 'Object'] }], // 禁止額外的 bind 'no-extra-bind': 2, // 禁止額外的布爾值轉換 'no-extra-boolean-cast': 2, // 禁止額外的 label 'no-extra-label': 2, // 禁止額外的括號,僅針對函數體 'no-extra-parens': [2, 'functions'], // 禁止額外的分號 'no-extra-semi': 2, // 每一個 switch 的 case 都需要有 break, return 或 throw // 包含注釋的情況下允許 'no-fallthrough': [2, { 'commentPattern': '.' }], // 不允許使用 2. 或 .5 來表示數字,需要用 2、2.0、0.5 的格式 'no-floating-decimal': 2, // 禁止對函數聲明重新賦值 'no-func-assign': 2, // 禁止對全局變量賦值 'no-global-assign': 2, // 禁止使用隱式類型轉換 'no-implicit-coercion': [2, { 'allow': ['+', '!!'] // 允許 + 轉數值 '' + 轉字符串和 !! 轉布爾值 }], // 禁止在 setTimeout 和 setInterval 中傳入字符串,因會觸發隱式 eval 'no-implied-eval': 2, // 禁止隱式定義全局變量 'no-implicit-globals': 2, // 禁止行內注釋 // @off 很常用 'no-inline-comments': 0, // 禁止在塊作用域內使用 var 或函數聲明 'no-inner-declarations': [2, 'both'], // 禁止使用非法的正則表達式 'no-invalid-regexp': 2, // 禁止在類之外的地方使用 this // @off this 的使用很靈活,事件回調中可以表示當前元素,函數也可以先用 this,等以后被調用的時候再 call 'no-invalid-this': 0, // 禁止使用不規范空格 'no-irregular-whitespace': [2, { 'skipStrings': true, // 允許在字符串中使用 'skipComments': true, // 允許在注釋中使用 'skipRegExps': true, // 允許在正則表達式中使用 'skipTemplates': true, // 允許在模板字符串中使用 }], // 禁止使用 __iterator__ 'no-iterator': 2, // label 不得與已定義的變量重名 'no-label-var': 2, // 禁止使用 label // @off 禁止了將很難 break 多重循環和多重 switch 'no-labels': 0, // 禁止使用無效的塊作用域 'no-lone-blocks': 2, // 禁止 else 中只有一個單獨的 if // @off 單獨的 if 可以把邏輯表達的更清楚 'no-lonely-if': 0, // 禁止 for (var i) { function() { use i } },使用 let 則可以 'no-loop-func': 2, // 禁止魔法數字 'no-magic-numbers': 0, // 禁止使用混合的邏輯判斷,必須把不同的邏輯用圓括號括起來 'no-mixed-operators': [2, { "groups": [ ["&&", "||"] ] }], // 相同類型的 require 必須放在一起 // @off 不限制 'no-mixed-requires': 0, // 禁止混用空格和 tab 來做縮進,必須統一 'no-mixed-spaces-and-tabs': 2, // 禁止連等賦值 'no-multi-assign': 2, // 禁止使用連續的空格 'no-multi-spaces': 2, // 禁止使用 \ 來定義多行字符串,統一使用模板字符串來做 'no-multi-str': 2, // 連續空行的數量限制 'no-multiple-empty-lines': [2, { max: 3, // 文件內最多連續 3 個 maxEOF: 1, // 文件末尾最多連續 1 個 maxBOF: 1 // 文件頭最多連續 1 個 }], // 禁止 if 中出現否定表達式 !== // @off 否定的表達式可以把邏輯表達的更清楚 'no-negated-condition': 0, // 禁止嵌套的三元表達式 // @off 沒有必要限制 'no-nested-ternary': 0, // 禁止 new Function // @off 有時會用它來解析非標准格式的 JSON 數據 'no-new-func': 0, // 禁止使用 new Object 'no-new-object': 2, // 禁止使用 new require 'no-new-require': 2, // 禁止使用 new Symbol 'no-new-symbol': 2, // 禁止 new Boolean、Number 或 String 'no-new-wrappers': 2, // 禁止 new 一個類而不存儲該實例 'no-new': 2, // 禁止把原生對象 Math、JSON、Reflect 當函數使用 'no-obj-calls': 2, // 禁止使用八進制轉義符 'no-octal-escape': 2, // 禁止使用0開頭的數字表示八進制 'no-octal': 2, // 禁止使用 __dirname + 'file' 的形式拼接路徑,應該使用 path.join 或 path.resolve 來代替 'no-path-concat': 2, // 禁止對函數的參數重新賦值 'no-param-reassign': 2, // 禁止 ++ 和 -- // @off 很常用 'no-plusplus': 0, // 禁止使用 process.env.NODE_ENV // @off 使用很常見 'no-process-env': 0, // 禁止使用 process.exit(0) // @off 使用很常見 'no-process-exit': 0, // 禁止使用 hasOwnProperty, isPrototypeOf 或 propertyIsEnumerable // @off 與 guard-for-in 規則沖突,且沒有必要 'no-prototype-builtins': 0, // 禁止使用 __proto__ 'no-proto': 2, // 禁止重復聲明 'no-redeclare': 2, // 禁止在正則表達式中出現連續空格 'no-regex-spaces': 2, // 禁止特定的全局變量 // @off 暫時沒有 'no-restricted-globals': 0, // 禁止 import 特定的模塊 // @off 暫時沒有 'no-restricted-imports': 0, // 禁止使用特定的模塊 // @off 暫時沒有 'no-restricted-modules': 'off', // 禁止特定的對象屬性 // @off 暫時沒有 'no-restricted-properties': 0, // 禁止使用特定的語法 // @off 暫時沒有 'no-restricted-syntax': 0, // 禁止在return中賦值 'no-return-assign': 2, // 禁止在 return 中使用 await 'no-return-await': 2, // 禁止 location.href = 'javascript:void' 'no-script-url': 2, // 禁止將自己賦值給自己 'no-self-assign': 2, // 禁止自己與自己作比較 'no-self-compare': 2, // 禁止逗號操作符 'no-sequences': 2, // 禁止使用保留字作為變量名 'no-shadow-restricted-names': 2, // 禁止在嵌套作用域中出現重名的定義,如 let a; function b() { let a } 'no-shadow': 2, // 禁止數組中出現連續逗號 'no-sparse-arrays': 2, // 禁止使用 node 中的同步的方法,比如 fs.readFileSync // @off 使用很常見 'no-sync': 0, // 禁止使用 tabs // @off 不限制 'no-tabs': 0, // 禁止普通字符串中出現模板字符串語法 'no-template-curly-in-string': 2, // 禁止三元表達式 // @off 很常用 'no-ternary': 0, // 禁止在構造函數的 super 之前使用 this 'no-this-before-super': 2, // 禁止 throw 字面量,必須 throw 一個 Error 對象 'no-throw-literal': 2, // 禁止行尾空格 'no-trailing-spaces': [2, { "skipBlankLines": true, // 不檢查空行 "ignoreComments": true // 不檢查注釋 }], // 禁止將 undefined 賦值給變量 'no-undef-init': 2, // 禁止訪問未定義的變量或方法 'no-undef': 2, // 禁止使用 undefined,如需判斷一個變量是否為 undefined,請使用 typeof a === 'undefined' 'no-undefined': 2, // 禁止變量名中使用下划線 // @off 暫不限制 'no-underscore-dangle': 0, // 禁止出現難以理解的多行代碼 'no-unexpected-multiline': 2, // 循環體內必須對循環條件進行修改 'no-unmodified-loop-condition': 2, // 禁止不必要的三元表達式 'no-unneeded-ternary': [2, { 'defaultAssignment': false }], // 禁止出現不可到達的代碼,如在 return、throw 之后的代碼 'no-unreachable': 2, // 禁止在finally塊中出現 return、throw、break、continue 'no-unsafe-finally': 2, // 禁止出現不安全的否定,如 for (!key in obj} {},應該寫為 for (!(key in obj)} {} 'no-unsafe-negation': 2, // 禁止出現無用的表達式 'no-unused-expressions': [2, { 'allowShortCircuit': true, // 允許使用 a() || b 或 a && b() 'allowTernary': true, // 允許在表達式中使用三元運算符 'allowTaggedTemplates': true, // 允許標記模板字符串 } ], // 禁止定義不使用的 label 'no-unused-labels': 2, // 禁止定義不使用的變量 'no-unused-vars': [2, { 'vars': 'all', // 變量定義必須被使用 'args': 'none', // 對於函數形參不檢測 'ignoreRestSiblings': true, // 忽略剩余子項 fn(...args),{a, b, ...coords} 'caughtErrors': 'none', // 忽略 catch 語句的參數使用 } ], // 禁止在變量被定義之前使用它 'no-use-before-define': [2, { 'functions': false, // 允許函數在定義之前被調用 'classes': false, // 允許類在定義之前被引用 } ], // 禁止不必要的 call 和 apply 'no-useless-call': 2, // 禁止使用不必要計算的key,如 var a = { ['0']: 0 } 'no-useless-computed-key': 2, // 禁止不必要的字符串拼接 'no-useless-concat': 2, // 禁止無用的構造函數 'no-useless-constructor': 2, // 禁止無用的轉義 'no-useless-escape': 2, // 禁止無效的重命名,如 import {a as a} from xxx 'no-useless-rename': 2, // 禁止沒有必要的 return // @off 沒有必要限制 'no-useless-return': 0, // 禁止使用 var,必須用 let 或 const 'no-var': 2, // 禁止使用void 'no-void': 2, // 禁止注釋中出現 TODO 或 FIXME,用這個來提醒開發者,寫了 TODO 就一定要做完 'no-warning-comments': 1, // 禁止屬性前出現空格,如 foo. bar() 'no-whitespace-before-property': 2, // 禁止 with 'no-with': 2, // 禁止 if 語句在沒有花括號的情況下換行 'nonblock-statement-body-position': 2, // 定義對象的花括號前后是否要加空行 // @off 不關心 'object-curly-newline': 0, // 定義對象的花括號前后是否要加空格 // @off 不關心 'object-curly-spacing': 0, // 對象每個屬性必須獨占一行 // @off 不限制 'object-property-newline': 0, // obj = { a: a } 必須轉換成 obj = { a } // @off 沒必要 'object-shorthand': 0, // 每個變量聲明必須獨占一行 // @off 有 one-var 就不需要此規則了 'one-var-declaration-per-line': 0, // 是否允許使用逗號一次聲明多個變量 'one-var': [2, { 'const': 'never' // 所有 const 聲明必須獨占一行,不允許用逗號定義多個 }], // 必須使用 x = x + y 而不是 x += y // @off 沒必要限制 'operator-assignment': 0, // 斷行時操作符位於行首還是行尾 // @off 不關心 'operator-linebreak': 0, // 代碼塊首尾必須要空行 // @off 沒必要限制 'padded-blocks': 0, // 限制語句之間的空行規則,比如變量定義完之后必須要空行 // @off 沒必要限制 'padding-line-between-statements': 0, // 必須使用箭頭函數作為回調 // @off 沒必要 'prefer-arrow-callback': 0, // 聲明后不再修改的變量必須使用 const // @off 沒必要 'prefer-const': 0, // 必須使用解構 // @off 沒必要 'prefer-destructuring': 0, // 必須使用 0b11111011 而不是 parseInt('111110111', 2) // @off 沒必要 'prefer-numeric-literals': 0, // promise 的 reject 中必須傳入 Error 對象,而不允許使用字面量 'prefer-promise-reject-errors': 2, // 必須使用解構 ...args 來代替 arguments 'prefer-rest-params': 2, // 必須使用 func(...args) 來代替 func.apply(args) // @off 沒必要 'prefer-spread': 0, // 必須使用模板字符串來代替字符串拼接 // @off 不限制 'prefer-template': 0, // 字符串必須使用單引號 'quotes': [2, 'single', { 'avoidEscape': true, // 允許包含單引號的字符串使用雙引號 'allowTemplateLiterals': true, // 允許使用模板字符串 }], // 對象字面量的鍵名禁止用引號括起來 // @off 沒必要限制 'quote-props': 0, // parseInt方法必須傳進制參數 'radix': 2, // async 函數中必須存在 await 語句 // @off async function 中沒有 await 的寫法很常見,比如 koa 的示例中就有這種用法 'require-await': 0, // 必須使用 jsdoc 風格的注釋 // @off 暫不考慮開啟 'require-jsdoc': 0, // generator 函數內必須有 yield 'require-yield': 2, // ...后面不允許有空格 'rest-spread-spacing': [2, 'never'], // 分號前后的空格規則 // @off 不限制 'semi-spacing': 0, // 禁止行首出現分號 'semi-style': [2, 'last'], // 行尾必須使用分號結束 'semi': 2, // imports 必須排好序 // @off 沒必要限制 'sort-imports': 0, // 對象字面量的鍵名必須排好序 // @off 沒必要限制 'sort-keys': 0, // 變量聲明必須排好序 // @off 沒必要限制 'sort-vars': 0, // function 等的花括號之前是否使用空格 // @off 不關心 'space-before-blocks': 0, // function 的圓括號之前是否使用空格 // @off 不關心 'space-before-function-paren': 0, // 圓括號內的空格使用規則 // @off 不關心 'space-in-parens': 0, // 操作符前后要加空格 'space-infix-ops': 2, // new, delete, typeof, void, yield 等表達式前后必須有空格,-, +, --, ++, !, !! 等表達式前后不許有空格 'space-unary-ops': [2, { 'words': true, 'nonwords': false, }], // 注釋的斜線和星號后要加空格 'spaced-comment': [2, 'always', { 'block': { exceptions: ['*'], balanced: true } }], // 禁用嚴格模式,禁止在任何地方出現 'use strict' 'strict': [2, 'never'], // switch 中冒號前后的空格規則 // @off 不關心 'switch-colon-spacing': 0, // 創建 Symbol 的時候必須傳入描述 'symbol-description': 2, // 模板字符串 ${} 前后的空格規則 // @off 不限制 'template-curly-spacing': 0, // 模板字符串前后的空格規則 // @off 不限制 'template-tag-spacing': 0, // 所有文件頭禁止出現 BOM 'unicode-bom': 2, // 禁止直接對 NaN 進行判斷,必須使用 isNaN 'use-isnan': 2, // 注釋必須符合 jsdoc 的規范 // @off 暫不考慮開啟 'valid-jsdoc': 0, // typeof 判斷條件只能是 "undefined", "object", "boolean", "number", "string", "function" 或 "symbol" 'valid-typeof': 2, // var 必須在作用域的最前面 // @off var 不在最前面也是很常見的用法 'vars-on-top': 0, // 自執行函數必須使用圓括號括起來,如 (function(){do something...})() 'wrap-iife': [2, 'inside'], // 正則表達式必須用圓括號括起來 // @off 不限制 'wrap-regex': 0, // yield 的 * 前后空格規則 // @off 不限制 'yield-star-spacing': 0, // 禁止Yoda格式的判斷條件,如 if (true === a),應使用 if (a === true) 'yoda': 2, } };
- ……
vscode配置補充
以下是vscode的settings.json文件
{ //設置eslintrc.json文件位置 "eslint.options": { "configFile": "C:/mydirectory/.eslintrc.json" }, //設置eslint檢查的文件類型,html非默認類型,需要手動添加 "eslint.validate": ["javascript", "javascriptreact", { "language": "html", "autoFix": true }], //eslint插件的目錄 "eslint.workingDirectories": [ "./client", "./server" ] }
更多信息請查看官網
ESLint中支持typescript
有關於ESlint和TypeScript,以及TSLint的相關知識,可以去看我翻譯加整理的另一篇文章。這里大致說一下應用原理,無論是Javascript還是TypeScript,都使用解析器生成AST(語法樹),但是兩者的AST有差異。如果要使用ESLint檢查TypeScript,使用@typescript-eslint/parser解析器(實際上需要解析器和多個插件的配合),這個解析器將TypeScript轉換成ESLint中可以兼容的格式。
@typescript-eslint/parser下面的文字說明了,設置解析器同時也需要設置parserOptions,這樣才可以正確使用
- 安裝@typescript-eslint/parser
npm install @typescript-eslint/parser --save-dev
- 在ESLint的配置文件中增加解析器配置,關於配置的詳細解釋,下面的parserOptions配置只是一個例子,舉例說明支持哪些參數
- 還需要使用另一個插件,它將添加或擴展具有特定於類型的特性的規則。可以選擇@typescript-eslint/eslint-plugin或者@typescript-eslint/eslint-plugin-tslint;
這里需要注意插件和解析器所支持的TypeScript版本://安裝@typescript-eslint/eslint-plugin npm i @typescript-eslint/eslint-plugin --save-dev
一定要保證@typescript-esling/parser和@typescript-eslint/eslint-plugin版本一致。還有如果eslint是全局安裝,@typescript-eslint/eslint-plugin也必須全局安裝。開發過程中,鑒於插件、庫等等的版本多樣,局部安裝特定的版本是一個不錯的選擇。
- 接下來配置,官網地址
首先添加解析器配置,並且添加插件:
{ "parser": "@typescript-eslint/parser", "plugins": ["@typescript-eslint"] }
如果需要添加檢查代碼的規則:
{ "parser": "@typescript-eslint/parser", "plugins": ["@typescript-eslint"], "rules": { "@typescript-eslint/rule-name": "error" } }
如果希望使用默認推薦的規則:
{ "extends": ["plugin:@typescript-eslint/recommended"] }
如果eslint的代碼檢查也想要使用默認推薦規則:
{ "extends": [ "eslint:recommended", "plugin:@typescript-eslint/eslint-recommended", "plugin:@typescript-eslint/recommended" ] }
如果希望使用類型信息的規則,需要指定tsconfig.json的地址,在parserOptions的project中指定。
{ "parser": "@typescript-eslint/parser", "parserOptions": { "project": "./tsconfig.json" }, "plugins": ["@typescript-eslint"], "rules": { "@typescript-eslint/restrict-plus-operands": "error" } }
- <可選>可以結合Prettier一起使用,為了格式,有可能關閉不必要的規則或者與prettier沖突的規則,安裝配置詳細
//安裝 npm install --save-dev eslint-config-prettier //配置,一下是所有支持的配置,可以根據需要選擇 { "extends": [ "plugin:@typescript-eslint/recommended", "prettier", "prettier/@typescript-eslint", "prettier/babel", "prettier/flowtype", "prettier/react", "prettier/standard", "prettier/unicorn", "prettier/vue" ] }
//安裝 npm install --save-dev eslint-config-prettier //配置,一下是所有支持的配置,可以根據需要選擇 { "extends": [ "plugin:@typescript-eslint/recommended", "prettier", "prettier/@typescript-eslint", "prettier/babel", "prettier/flowtype", "prettier/react", "prettier/standard", "prettier/unicorn", "prettier/vue" ] }
注意:版本為
eslint-config-prettier@4.0.0或者更新的版本
- 配合Airbnb一起使用,如果不包含React,使用eslint-config-airbnb-base,否則使用eslint-config-airbnb。具體細節可以查看這里。
//安裝Airbnb語法負責,以及安裝import,ally,react插件 npm i -g eslint-config-airbnb npm i -g eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react //配置文件添加配置 { "extends": "eslint-config-airbnb" } //或者只添加extends:airbnb
- ……
錯誤記錄
自己動手從零配置項目會出現很多錯誤,解決的同時可以幫助我們了解配置屬性的功能。
vs code安裝ESLint不提示錯誤。
vs code中安裝了ESLint擴展,安裝了eslint,@typescript-eslint/parser以及@typescript-eslint/eslint-plugin,並且配置了.eslintrc.json文件。使用命令行eslint index.ts會顯示ts文件中的錯誤,但是在vscode中不能夠以紅色下划線提示。結果在output提示中,表示ESlint和@typescript-eslint/plugin安裝路徑不一致。
解決:卸載全局eslint。或者全局安裝@typescript-eslint/eslint-plugin。(雖然解決了,但但是對於npm包的查找和依賴產生疑問?)
ESlint Parsing Error : Unexpected token。
解答地址。出現錯誤的理由主要是ESLint解析功能與javascript版本之間出現不兼容而導致的。解析方式有多種。比如在.eslitnrc.json文件中的parserOptions屬性中聲明ecmaVersion。
"parserOptions": { "ecmaVersion": 6 }
還有其他方式,可以查看前面的解答地址。
Console is not defined.eslint報錯。
這個問題主要是因為運行環境的設置問題,在.eslintrc.json中設置env屬性,添加browser
"env": { "node": true, "browser": true }
cannot-redeclare-block-scoped-variable
.ts文件或者使用@ts-check的js文件,如果沒有明顯的模塊標識(import,export)等等,會被認為是全局的。聲明的變量與其他文件,vscode中,即使不是一個項目,也會提示該錯誤。解答地址與參考。
Parsing error: 'import' and 'export' may appear only with 'sourceType: module'
首先介紹一個出現這個的背景:因為使用了typescript,想要在js文件中添加typescript的類型檢查規則,於是在js添加了@ts-check,這時候出現了上一個記錄的問題,變量被識別為全局變量。於是為了解決這個問題,在文件中添加了export{ }語句,文件被識別為模塊文件。然后又出現了這個錯誤。解決方式,在eslintrc文件中設置sourceType為module。
{ "parserOptions": { ..."sourceType": "module"
} }
總結
全局安裝typescript
npm install typescript -g
本地安裝eslint
npm install eslint --save-dev
安裝eslint之后,新建並配置.eslintrc.json文件。recommonded表示使用默認推薦的檢查規則。
{ "extends": [ "eslint:recommended" ] }
安裝@typescript-eslint/parser,自定義的解析器,用於替代ESLint默認的解析器,結合了typescript-estree,幫助eslint檢查typescript代碼。
npm install @typescript-eslint/parser --save-dev
在eslintrc.文件中添加parser屬性聲明
{ "parser": "@typescript-eslint/parser", "extends": [ "eslint:recommended" ] }
安裝@typescript-eslint/eslint-plugin,幫助應用typescript的檢查規則
npm i @typescript-eslint/eslint-plugin --save-dev
在eslintrc.文件中添加plugins屬性聲明以及extends中添加plugin的兩項屬性值
{ "parser": "@typescript-eslint/parser", "extends": [ "eslint:recommended", "plugin:@typescript-eslint/eslint-recommended", "plugin:@typescript-eslint/recommended" ], "plugins": ["@typescript-eslint"] }
最后補充其他需要的配置聲明。
parserOptions用於指定你想要支持的 JavaScript 語言選項,比如ECMAScript的版本,文件類型等等。env包含了代碼中可以使用的全局變量,例如包含了browser才可以使用console。rules是最基本的功能,可以添加或者修改檢查規則。
{ "parser": "@typescript-eslint/parser", "plugins": ["@typescript-eslint"], "parserOptions": { "ecmaVersion": 6, "sourceType": "module" }, "extends": [ "eslint:recommended", "plugin:@typescript-eslint/eslint-recommended", "plugin:@typescript-eslint/recommended" ], "env": { "node": true, "browser": true, "commonjs": true, "es6": true, "jquery": true }, "rules": { "linebreak-style": ["error", "windows"] } }
參考
- 文章中的.eslintrc.js文件來自這里,一個博主的實際工程實踐
- eslintrc.js文件詳細配置——地址
- 有關ESLint的全部rules
- typescript-eslint/esling-plugin:規則
- typescript入門——項目配置