ESLint 的使用和.eslintrc.js配置

在團隊協(xié)作中,為避免低級 Bug、產(chǎn)出風(fēng)格統(tǒng)一的代碼,會預(yù)先制定編碼規(guī)范。使用 Lint 工具和代碼風(fēng)格檢測工具,則可以輔助編碼規(guī)范執(zhí)行,有效控制代碼質(zhì)量。

ESLint 簡介

ESLint 由 JavaScript 紅寶書 作者 Nicholas C. Zakas 編寫, 2013 年發(fā)布第一個版本。 NCZ 的初衷不是重復(fù)造一個輪子,而是在實際需求得不到 JSHint 團隊響應(yīng) 的情況下做出的選擇:以可擴展、每條規(guī)則獨立、不內(nèi)置編碼風(fēng)格為理念編寫一個 lint 工具。

ESLint 主要有以下特點:

  • 默認規(guī)則包含所有 JSLint、JSHint 中存在的規(guī)則,易遷移;
  • 規(guī)則可配置性高:可設(shè)置「警告」、「錯誤」兩個 error 等級,或者直接禁用;
  • 包含代碼風(fēng)格檢測的規(guī)則
  • 支持插件擴展、自定義規(guī)則

使用 ESLint

ESLint 詳盡使用參見 官方文檔 http://eslint.org/docs/user-guide/configuring

配置 ESLint

可以通過以下三種方式配置 ESLint:

  • 使用 .eslintrc 文件(支持 JSON 和 YAML 兩種語法);
  • 在 package.json 中添加 eslintConfig 配置塊;
  • 直接在代碼文件中定義。

.eslintrc 文件示例:

{
  "env": {
    "browser": true,
  },
  "globals": {
    "angular": true,
  },
  "rules": {
    "camelcase": 2,
    "curly": 2,
    "brace-style": [2, "1tbs"],
    "quotes": [2, "single"],
    "semi": [2, "always"],
    "space-in-brackets": [2, "never"],
    "space-infix-ops": 2,
  }
}

.eslintrc 放在項目根目錄,則會應(yīng)用到整個項目;如果子目錄中也包含 .eslintrc 文件,則子目錄會忽略根目錄的配置文件,應(yīng)用該目錄中的配置文件。這樣可以方便地對不同環(huán)境的代碼應(yīng)用不同的規(guī)則。

package.json 示例:

{
  "name": "mypackage",
  "version": "0.0.1",
  "eslintConfig":
  {
    "env": {
      "browser": true,
      "node": true
    }
  }
}

文件內(nèi)配置

代碼文件內(nèi)配置的規(guī)則會覆蓋配置文件里的規(guī)則。

.eslintrc 文件示例和解釋:

  {  
    "env": {  
      "browser": true,  
      "node": true,  
      "commonjs": true  
    },  
    "ecmaFeatures": {  
      // lambda表達式  
      "arrowFunctions": true,  
      // 解構(gòu)賦值  
      "destructuring": true,  
      // class  
      "classes": true,  
      // http://es6.ruanyifeng.com/#docs/function#函數(shù)參數(shù)的默認值  
      "defaultParams": true,  
      // 塊級作用域,允許使用let const  
      "blockBindings": true,  
      // 允許使用模塊,模塊內(nèi)默認嚴格模式  
      "modules": true,  
      // 允許字面量定義對象時,用表達式做屬性名  
      // http://es6.ruanyifeng.com/#docs/object#屬性名表達式  
      "objectLiteralComputedProperties": true,  
      // 允許對象字面量方法名簡寫  
      /*var o = {
          method() {
            return "Hello!";
          }
       };

       等同于

       var o = {
         method: function() {
           return "Hello!";
         }
       };
      */  
      "objectLiteralShorthandMethods": true,  
      /*
        對象字面量屬性名簡寫
        var foo = 'bar';
        var baz = {foo};
        baz // {foo: "bar"}

        // 等同于
        var baz = {foo: foo};
      */  
      "objectLiteralShorthandProperties": true,  
      // http://es6.ruanyifeng.com/#docs/function#rest參數(shù)  
      "restParams": true,  
      // http://es6.ruanyifeng.com/#docs/function#擴展運算符  
      "spread": true,  
      // http://es6.ruanyifeng.com/#docs/iterator#for---of循環(huán)  
      "forOf": true,  
      // http://es6.ruanyifeng.com/#docs/generator  
      "generators": true,  
      // http://es6.ruanyifeng.com/#docs/string#模板字符串  
      "templateStrings": true,  
      "superInFunctions": true,  
      // http://es6.ruanyifeng.com/#docs/object#對象的擴展運算符  
      "experimentalObjectRestSpread": true  
    },  

    "rules": {  
      // 定義對象的set存取器屬性時,強制定義get  
      "accessor-pairs": 2,  
      // 指定數(shù)組的元素之間要以空格隔開(,后面), never參數(shù):[ 之前和 ] 之后不能帶空格,always參數(shù):[ 之前和 ] 之后必須帶空格  
      "array-bracket-spacing": [2, "never"],  
      // 在塊級作用域外訪問塊內(nèi)定義的變量是否報錯提示  
      "block-scoped-var": 0,  
      // if while function 后面的{必須與if在同一行,java風(fēng)格。  
      "brace-style": [2, "1tbs", { "allowSingleLine": true }],  
      // 雙峰駝命名格式  
      "camelcase": 2,  
      // 數(shù)組和對象鍵值對最后一個逗號, never參數(shù):不能帶末尾的逗號, always參數(shù):必須帶末尾的逗號,  
      // always-multiline:多行模式必須帶逗號,單行模式不能帶逗號  
      "comma-dangle": [2, "never"],  
      // 控制逗號前后的空格  
      "comma-spacing": [2, { "before": false, "after": true }],  
      // 控制逗號在行尾出現(xiàn)還是在行首出現(xiàn)  
      // http://eslint.org/docs/rules/comma-style  
      "comma-style": [2, "last"],  
      // 圈復(fù)雜度  
      "complexity": [2,9],  
      // 以方括號取對象屬性時,[ 后面和 ] 前面是否需要空格, 可選參數(shù) never, always  
      "computed-property-spacing": [2,"never"],  
      // 強制方法必須返回值,TypeScript強類型,不配置  
      "consistent-return": 0,  
      // 用于指統(tǒng)一在回調(diào)函數(shù)中指向this的變量名,箭頭函數(shù)中的this已經(jīng)可以指向外層調(diào)用者,應(yīng)該沒卵用了  
      // e.g [0,"that"] 指定只能 var that = this. that不能指向其他任何值,this也不能賦值給that以外的其他值  
      "consistent-this": 0,  
      // 強制在子類構(gòu)造函數(shù)中用super()調(diào)用父類構(gòu)造函數(shù),TypeScrip的編譯器也會提示  
      "constructor-super": 0,  
      // if else while for do后面的代碼塊是否需要{ }包圍,參數(shù):  
      //    multi  只有塊中有多行語句時才需要{ }包圍  
      //    multi-line  只有塊中有多行語句時才需要{ }包圍, 但是塊中的執(zhí)行語句只有一行時,  
      //                   塊中的語句只能跟和if語句在同一行。if (foo) foo++; else doSomething();  
      //    multi-or-nest 只有塊中有多行語句時才需要{ }包圍, 如果塊中的執(zhí)行語句只有一行,執(zhí)行語句可以零另起一行也可以跟在if語句后面  
      //    [2, "multi", "consistent"] 保持前后語句的{ }一致  
      //    default: [2, "all"] 全都需要{ }包圍  
      "curly": [2, "all"],  
      // switch語句強制default分支,也可添加 // no default 注釋取消此次警告  
      "default-case": 2,  
      // 強制object.key 中 . 的位置,參數(shù):  
      //      property,'.'號應(yīng)與屬性在同一行  
      //      object, '.' 號應(yīng)與對象名在同一行  
      "dot-location": [2, "property"],  
      // 強制使用.號取屬性  
      //    參數(shù): allowKeywords:true 使用保留字做屬性名時,只能使用.方式取屬性  
      //                          false 使用保留字做屬性名時, 只能使用[]方式取屬性 e.g [2, {"allowKeywords": false}]  
      //           allowPattern:  當屬性名匹配提供的正則表達式時,允許使用[]方式取值,否則只能用.號取值 e.g [2, {"allowPattern": "^[a-z]+(_[a-z]+)+$"}]  
      "dot-notation": [2, {"allowKeywords": true}],  
      // 文件末尾強制換行  
      "eol-last": 2,  
      // 使用 === 替代 ==  
      "eqeqeq": [2, "allow-null"],  
      // 方法表達式是否需要命名  
      "func-names": 0,  
      // 方法定義風(fēng)格,參數(shù):  
      //    declaration: 強制使用方法聲明的方式,function f(){} e.g [2, "declaration"]  
      //    expression:強制使用方法表達式的方式,var f = function() {}  e.g [2, "expression"]  
      //    allowArrowFunctions: declaration風(fēng)格中允許箭頭函數(shù)。 e.g [2, "declaration", { "allowArrowFunctions": true }]  
      "func-style": 0,  
      "generator-star-spacing": [2, { "before": true, "after": true }],  
      "guard-for-in": 0,  
      "handle-callback-err": [2, "^(err|error)$" ],  
      "indent": [2, 2, { "SwitchCase": 1 }],  
      "key-spacing": [2, { "beforeColon": false, "afterColon": true }],  
      "linebreak-style": 0,  
      "lines-around-comment": 0,  
      "max-nested-callbacks": 0,  
      "new-cap": [2, { "newIsCap": true, "capIsNew": false }],  
      "new-parens": 2,  
      "newline-after-var": 0,  
      "no-alert": 0,  
      "no-array-constructor": 2,  
      "no-caller": 2,  
      "no-catch-shadow": 0,  
      "no-cond-assign": 2,  
      "no-console": 0,  
      "no-constant-condition": 0,  
      "no-continue": 0,  
      "no-control-regex": 2,  
      "no-debugger": 2,  
      "no-delete-var": 2,  
      "no-div-regex": 0,  
      "no-dupe-args": 2,  
      "no-dupe-keys": 2,  
      "no-duplicate-case": 2,  
      "no-else-return": 0,  
      "no-empty": 0,  
      "no-empty-character-class": 2,  
      "no-empty-label": 2,  
      "no-eq-null": 0,  
      "no-eval": 2,  
      "no-ex-assign": 2,  
      "no-extend-native": 2,  
      "no-extra-bind": 2,  
      "no-extra-boolean-cast": 2,  
      "no-extra-parens": 0,  
      "no-extra-semi": 0,  
      "no-fallthrough": 2,  
      "no-floating-decimal": 2,  
      "no-func-assign": 2,  
      "no-implied-eval": 2,  
      "no-inline-comments": 0,  
      "no-inner-declarations": [2, "functions"],  
      "no-invalid-regexp": 2,  
      "no-irregular-whitespace": 2,  
      "no-iterator": 2,  
      "no-label-var": 2,  
      "no-labels": 2,  
      "no-lone-blocks": 2,  
      "no-lonely-if": 0,  
      "no-loop-func": 0,  
      "no-mixed-requires": 0,  
      "no-mixed-spaces-and-tabs": 2,  
      "no-multi-spaces": 2,  
      "no-multi-str": 2,  
      "no-multiple-empty-lines": [2, { "max": 1 }],  
      "no-native-reassign": 2,  
      "no-negated-in-lhs": 2,  
      "no-nested-ternary": 0,  
      "no-new": 2,  
      "no-new-func": 0,  
      "no-new-object": 2,  
      "no-new-require": 2,  
      "no-new-wrappers": 2,  
      "no-obj-calls": 2,  
      "no-octal": 2,  
      "no-octal-escape": 2,  
      "no-param-reassign": 0,  
      "no-path-concat": 0,  
      "no-process-env": 0,  
      "no-process-exit": 0,  
      "no-proto": 0,  
      "no-redeclare": 2,  
      "no-regex-spaces": 2,  
      "no-restricted-modules": 0,  
      "no-return-assign": 2,  
      "no-script-url": 0,  
      "no-self-compare": 2,  
      "no-sequences": 2,  
      "no-shadow": 0,  
      "no-shadow-restricted-names": 2,  
      "no-spaced-func": 2,  
      "no-sparse-arrays": 2,  
      "no-sync": 0,  
      "no-ternary": 0,  
      "no-this-before-super": 2,  
      "no-throw-literal": 2,  
      "no-trailing-spaces": 2,  
      "no-undef": 2,  
      "no-undef-init": 2,  
      "no-undefined": 0,  
      "no-underscore-dangle": 0,  
      "no-unexpected-multiline": 2,  
      "no-unneeded-ternary": 2,  
      "no-unreachable": 2,  
      "no-unused-expressions": 0,  
      "no-unused-vars": [2, { "vars": "all", "args": "none" }],  
      "no-use-before-define": 0,  
      "no-var": 0,  
      "no-void": 0,  
      "no-warning-comments": 0,  
      "no-with": 2,  
      "object-curly-spacing": 0,  
      "object-shorthand": 0,  
      "one-var": [2, { "initialized": "never" }],  
      "operator-assignment": 0,  
      "operator-linebreak": [2, "after", { "overrides": { "?": "before", ":": "before" } }],  
      "padded-blocks": 0,  
      "prefer-const": 0,  
      "quote-props": 0,  
      "quotes": [2, "single", "avoid-escape"],  
      "radix": 2,  
      "semi": [2, "never"],  
      "semi-spacing": 0,  
      "sort-vars": 0,  
      "space-after-keywords": [2, "always"],  
      "space-before-blocks": [2, "always"],  
      "space-before-function-paren": [2, "always"],  
      "space-in-parens": [2, "never"],  
      "space-infix-ops": 2,  
      "space-return-throw-case": 2,  
      "space-unary-ops": [2, { "words": true, "nonwords": false }],  
      "spaced-comment": [2, "always", { "markers": ["global", "globals", "eslint", "eslint-disable", "*package", "!"] }],  
      "strict": 0,  
      "use-isnan": 2,  
      "valid-jsdoc": 0,  
      "valid-typeof": 2,  
      "vars-on-top": 0,  
      "wrap-iife": [2, "any"],  
      "wrap-regex": 0,  
      "yoda": [2, "never"]  
    }  
  }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • ESLint 配置 ESlint 被設(shè)計為完全可配置的,這意味著你可以關(guān)閉每一個規(guī)則而只運行基本語法驗證,或混合和...
    靜默虛空閱讀 41,853評論 3 14
  • 兩個月之前在項目中就開始使用 Eslint ,當時直接 copy 別人的 .eslintrc.js 文件,感覺好復(fù)...
    dkvirus閱讀 112,563評論 33 190
  • EsLint入門學(xué)習(xí)整理 這兩天因為公司要求,就對ESLint進行了初步的了解,網(wǎng)上的內(nèi)容基本上都差不多,但是內(nèi)容...
    點柈閱讀 26,238評論 3 42
  • ESLint 配置 中文官網(wǎng) 簡介 ESLint 是在 ECMAScript/JavaScript 代碼中識別和報...
    zcynine閱讀 1,837評論 0 1
  • 通常在我們定義靜態(tài)方法,返回實例對象時,將返回值類型定義成instancetype,除了instancetype修...
    ShenYj閱讀 365評論 0 1

友情鏈接更多精彩內(nèi)容