ESLint 使用指南


ESLint 官方文檔 About 頁面 分 About 和 Philosophy 兩個部分對 ESLint 做了介紹,簡潔明了,值得一讀。

借助 ESLint,可將 靜態代碼分析問題代碼協助修復 集成到 編碼提交打包 過程中,及早發現並協助修復代碼中:

  • 有語法錯誤的部分
  • 不符合約定的樣式准則的部分
  • 不符合約定的最佳實踐的部分

在項目開發中獲得如下收益:

  • 在執行代碼之前發現並修復語法錯誤,減少調試耗時和潛在 bug
  • 保證項目的編碼風格統一,提高可維護性
  • 督促團隊成員在編碼時遵守約定的最佳實踐,提高代碼質量

安裝

# Local Installation
npm install -D eslint

# Global Installation
npm install -g eslint

注意

  • ESLint 借助 nodejs 的模塊化機制引用插件。所以,全局安裝的 ESLint 只能使用全局安裝的 ESLint 插件,局部安裝的 ESLint 只能使用局部安裝的 ESLint 插件。

命令行接口

官方文檔:eslint.org/docs/user-g…

 

命令模式

# eslint [選項] [操作目標]
eslint [options] [file|dir|glob]*

注意

  • 當使用 glob 語法指定操作目標時,glob 模式會被 shell 解析,解析結果可能因 shell 不同而不同。如果想要使用 nodeglob 語法,必須使用引號將 glob 模式串引起來(在 Windows 中必須使用雙引號)。示例:

eslint "lib/**"

命令選項

使用 ESLint 命令時,可以通過 eslint -h 概覽命令選項,找到自己需要的選項,然后去官方文檔 命令行接口部分 查看該選項的詳細描述。

eslint [options] file.js [file.js] [dir]

Basic configuration:
  --no-eslintrc                  Disable use of configuration from .eslintrc.*
  -c, --config path::String      Use this configuration, overriding .eslintrc.* config options if present
  --env [String]                 Specify environments
  --ext [String]                 Specify JavaScript file extensions - default: .js
  --global [String]              Define global variables
  --parser String                Specify the parser to be used
  --parser-options Object        Specify parser options
  --resolve-plugins-relative-to path::String  A folder where plugins should be resolved from, CWD by default

Specifying rules and plugins:
  --rulesdir [path::String]      Use additional rules from this directory
  --plugin [String]              Specify plugins
  --rule Object                  Specify rules

Fixing problems:
  --fix                          Automatically fix problems
  --fix-dry-run                  Automatically fix problems without saving the changes to the file system
  --fix-type Array               Specify the types of fixes to apply (problem, suggestion, layout)

Ignoring files:
  --ignore-path path::String     Specify path of ignore file
  --no-ignore                    Disable use of ignore files and patterns
  --ignore-pattern [String]      Pattern of files to ignore (in addition to those in .eslintignore)

Using stdin:
  --stdin                        Lint code provided on <STDIN> - default: false
  --stdin-filename String        Specify filename to process STDIN as

Handling warnings:
  --quiet                        Report errors only - default: false
  --max-warnings Int             Number of warnings to trigger nonzero exit code - default: -1

Output:
  -o, --output-file path::String  Specify file to write report to
  -f, --format String            Use a specific output format - default: stylish
  --color, --no-color            Force enabling/disabling of color

Inline configuration comments:
  --no-inline-config             Prevent comments from changing config or rules
  --report-unused-disable-directives  Adds reported errors for unused eslint-disable directives

Caching:
  --cache                        Only check changed files - default: false
  --cache-file path::String      Path to the cache file. Deprecated: use --cache-location - default: .eslintcache
  --cache-location path::String  Path to the cache file or directory

Miscellaneous:
  --init                         Run config initialization wizard - default: false
  --debug                        Output debugging information
  -h, --help                     Show help
  -v, --version                  Output the version number
  --print-config path::String    Print the configuration for the given file

 

有些選項可接收一組參數,這類選項支持兩種傳參方式(有一個選項例外:--ignore-pattern 不支持第二種方式):

  1. 多次指定同一選項,每次接收一個不同的參數
  2. 將參數列表用逗號分隔,一次傳給選項

示例:

# 1.
eslint --ext .jsx --ext .js lib/

# 2.
eslint --ext .jsx,.js lib/

 

配置

相對路徑解析

配置文件中包含的相對路徑和 glob 模式都是基於當前配置文件的路徑進行解析的。

兩種主要的配置方式

  1. 配置注釋 - 在目標文件中使用注釋語法嵌入配置信息。這種配置只對當前文件有效。
  2. 配置文件 - 在 JavaScriptJSONYAML 文件中定義配置信息。對於這種配置方式,配置信息可以寫在單獨的  .eslintrc.*  文件中,或者寫在  package.json  文件的 eslintConfig  字段中。這種配置對配置文件所在目錄及其子目錄樹中的所有文件有效。

配置文件格式

  • JavaScript - use  .eslintrc.js  文件導出一個包含配置信息的對象。
  • YAML - 使用  .eslintrc.yaml  或  .eslintrc.yml  定義配置。
  • JSON - 使用  .eslintrc.json  定義配置信息,JSON 文件中支持 JavaScript 注釋。
  • package.json - 在  package.json  文件中增加一個 eslintConfig 字段,在該字段中定義配置信息。
  • .eslintrc - 已廢棄

如果在同一個目錄中有多個配置文件,則它們中間只有一個是有效的,優先級如下:

  1. .eslintrc.js
  2. .eslintrc.yaml 
  3. .eslintrc.yml
  4. .eslintrc.json
  5. .eslintrc 
  6. package.json

配置層疊

官方文檔: eslint.org/docs/user-g…
 

項目級配置文件

在同一個項目中,可以為不同目錄指定不同的配置文件。

當 lint 一個文件時,ESLint :

  1. 從文件所在目錄開始,在目錄樹中依次向上搜索配置文件,直到系統根目錄,或者直到找到一個包含  root: true  配置參數的配置文件,最終得到一個配置文件列表。
  2. 合並上一步得到的配置文件列表中的配置項,得到最終的配置文件配置。合並配置項時,在目錄樹中距離 lint 目標越近的配置文件具有越高的優先級。
  3. 執行其余步驟。

我覺得總結下來就是:找到 root: true 就停止尋找配置文件,多配置合並,配置文件優先級就近。

完整的配置層疊關系

ESLint 配置除了通過配置文件指定,還可以通過注釋內嵌或命令行選項指定。Lint 一個文件所使用的最終配置是各種配置合並的結果,合並時各種配置的優先級如下:

  1. 注釋內嵌配置

    1. /*eslint-disable*/ and /*eslint-enable*/
    2. /*global*/
    3. /*eslint*/
    4. /*eslint-env*/
  2. 通過命令行選項指定的配置

    1. --global
    2. --rule
    3. --env
    4. -c, --config
  3. 項目級配置文件

  4. 如果沒有找到項目級配置文件,並且沒有或沒有找到通過 --config 指定配置文件,則去用戶家目錄(~/)下搜索配置文件。

如果上述配置均不存在,則 ESLint 拋出 noConfigError 。

 

配置參數(各個參數詳解

  • parser

    指定 ESLint 使用的語法分析器。ESLint 兼容的語法分析器有:EsprimaBabel-ESLint@typescript-eslint/parser,ESLint 默認使用 Esprima

  • parserOptions

    指定語法分析器選項,默認使用的語法分析器支持如下幾個選項: ecmaVersion 、 sourceType 、 ecmaFeatures 。示例:

    {
      "parserOptions": {
        "ecmaVersion": 6,
        "sourceType": "module",
        "ecmaFeatures": {
          "jsx": true
        }
      }
    }

    不同的語法分析器可能具有不同的選項。

  • env

    指定執行環境,一個執行環境會預定義一組全局變量。示例:

    使用注釋配置

    /* eslint-env node, mocha */

     

    使用配置文件:

    {
      "env": {
        "browser": true,
        "node": true
      }
    }
     
  • globals

    使用未在當前文件中定義的全局變量時,會命中  no-undef  規則,通過 globals 配置指定的全局變量無視  no-undef  規則。示例:

    使用注釋配置

    /* global var1, var2 */
    
    /* global var1:writable, var2:writable */

     

    在配置文件中指定:

    {
      "globals": {
        "var1": "writable",
        "var2": "readonly"
      }
    }

     

  • plugins

    插件是第三方定制的規則集合,plugins參數用於指定第三方插件,雖然官方提供了上百種的規則可供選擇,但是這還不夠,因為官方的規則只能檢查標准的 JavaScript 語法,如果你寫的是 JSX 或者 Vue 單文件組件,ESLint 的規則就開始束手無策了,這個時候就需要安裝 ESLint 的插件,來定制一些特定的規則進行檢查,ESLint 的插件與擴展一樣有固定的命名格式,以  eslint-plugin- 開頭,插件名中的  eslint-plugin-  使用的時候也可以省略這個頭。示例:

    {
      "plugins": [
        "plugin1",
        "eslint-plugin-plugin2"
      ]
    }

    使用插件時必須安裝其 npm 包。

    注意

    • 受限於 Node 的模塊化機制,全局安裝的 ESLint 只能使用全局安裝的插件,局部安裝的 ESLint 只能使用局部安裝的插件,不支持全局插件和局部插件的混合使用。
  • rules

    指定 ESLint 校驗規則。

    所有規則獨立於其他規則,可單獨配置。

    ESLint 內置規則:eslint.org/docs/rules/

    規則組成:規則名、錯誤級別、附加選項

    規則配置模式:

    規則名: [錯誤級別, 附加選項]
    
    規則名: 錯誤級別
     

    示例:

    "rules": {
      "semi": ["error", "always"],
      "quotes": ["error", "double"]
    }

     

    在上述示例中,"semi""quotes" 是規則名,"error" 是規則錯誤級別,"always""quotes" 分別是 semiquotes 各自特有的附加選項。

    ESLint 定義了三種錯誤級別:

    • "off"0 - 關閉, 代表關閉此條規則,即不做關於此規則的檢測。
    • "warn"1 - 警告, 此條規則設置為需要進行warning警告的規則,eslint程序的返回碼不變。
    • "error"2 - 錯誤, 將此條規則設置為需要進行error報錯的規則,eslint程序的返回碼將變為1。。

    使用注釋配置

    /* eslint eqeqeq: "off", curly: "error" */
    
    // 如果規則有額外選項,可以用數組字面量語法
    /* eslint quotes: ["error", "double"], curly: 2 */

     

    使用配置文件

    {
      "rules": {
        "eqeqeq": "off",
        "curly": "error",
        "quotes": ["error", "double"]
      }
    }

     

    可在文件中使用注釋配置禁用全部規則或指定規則:

    • 塊級禁用

      /* eslint-disable */
      alert('foo');
      /* eslint-enable */
      
      /* eslint-disable no-alert, no-console */
      alert('foo');
      console.log('bar');
      /* eslint-enable no-alert, no-console */

       

    • 文件級禁用

      /* eslint-disable */
      alert('foo');
      
      /* eslint-disable no-alert */
      alert('foo');

       

    • 在指定行中禁用

      alert('foo'); // eslint-disable-line
      alert('foo'); // eslint-disable-line no-alert
      alert('foo'); // eslint-disable-line no-alert, quotes, semi
      alert('foo'); /* eslint-disable-line */
      alert('foo'); /* eslint-disable-line no-alert */
      alert('foo'); /* eslint-disable-line no-alert, quotes, semi   */
      
      // eslint-disable-next-line
      // eslint-disable-next-line no-alert
      // eslint-disable-next-line no-alert, quotes, semi
      /* eslint-disable-next-line */
      /* eslint-disable-next-line no-alert */
      /* eslint-disable-next-line no-alert, quotes, semi */
      alert('foo');

      /*eslint-disable*/ // 以下禁用檢查
      /*eslint-enable*/ // 以下啟用檢查
      /*global*/ // 全局
      /*eslint*/
      /*eslint-env*/ // 局部修改環境變量
      // eslint-disable-line // 當前行跳過檢查
      // eslint-disable-next-line // 下一行跳過檢查

       

  • overrides

    排除 ESLint 校驗規則。示例:

    {
      "rules": {...},
      "overrides": [
        {
          "files": ["*-test.js","*.spec.js"],
          "excludedFiles": "*.test.js",
          "rules": {
            "no-unused-expressions": "off"
          }
        }
      ]
    }

     

    對於匹配  overrides.files  且不匹配  overrides.excludedFiles  的 文件, overrides.rules  中的規則會覆蓋 rules  中的同名規則。

  • settings

    指定一個對象,這個對象會被提供給每一個將要執行的規則。

  • root

    ESLint 在目錄樹種搜索配置文件時,若遇到 root 參數為 true 的配置文件,就會停止搜索,否則沿着目錄樹一直向父級目錄的方向搜索到系統根目錄為止。

  • extends

    配置文件可以在已有配置的基礎上進行擴展,extends 用於指定基礎配置。該參數的值為以下之一:

    • 一個指定基礎配置來源的字符串
    • 一個指定基礎配置來源的字符串的數組:數組中每個配置擴展它前面的配置

    ESLint 支持遞歸擴展配置,所以基礎配置中也可包含 extends 參數,擴展就是直接使用別人已經寫好的 lint 規則,方便快捷。

    當指定基礎配置時,rules 參數指定的規則可按如下幾種方式進行擴展:

    • 啟用基礎配置中沒有規則
    • 繼承基礎配置中的規則,改變其錯誤級別,但不改變其附加選項:
      • 基礎配置: "eqeqeq": ["error", "allow-null"]
      • 擴展配置: "eqeqeq": "warn"
      • 最終有效配置:"eqeqeq": ["warn", "allow-null"]
    • 覆蓋基礎配置中的規則:
      • 基礎配置:"quotes": ["error", "single", "avoid-escape"]
      • 擴展配置:"quotes": ["error", "single"]
      • 最終有效配置: "quotes": ["error", "single"]

    使用 extends 指定的基礎配置來源可以是:

    • eslint:recommended,啟用 ESLint 內置規則集 的一個子集。

    • 共享配置包,一類導出 ESLint 配置對象的 npm 包,比如 eslint-config-standardeslint-config-airbnb 等。共享配置包需要安裝才能使用,配置時可省略報名中的 eslint-config- 前綴。如果你覺得自己的配置十分滿意,也可以將自己的 lint 配置發布到 npm 包,只要將包名命名為 eslint-config-xxx 即可,同時,需要在 package.json 的 peerDependencies 字段中聲明你依賴的 ESLint 的版本號。。

      示例:

      {
        "extends": ["airbnb"]
        "rules": {
          "no-set-state": "off"
        }
      }

       

    • 插件導出的命名配置, plugin 開頭的是擴展是插件類型,也可以直接在 plugins 屬性中進行設置,其配置值由以下幾部分組成:

      • plugin:
      • 插件包名(可省略前綴,例如:react
      • /
      • 配置名(例如:recommended

      示例:

      {
        "plugins": [
          "react"
        ],
        "extends": [
          "eslint:recommended",
          "plugin:react/recommended"
        ],
        "rules": {
          "no-set-state": "off"
        }
      }

       

    • 配置文件,通過配置文件的絕對路徑或相對路徑指定。

      示例:

      {
        "extends": [
          "./node_modules/coding-standard/eslintDefaults.js",
          "./node_modules/coding-standard/.eslintrc-es6",
          "./node_modules/coding-standard/.eslintrc-jsx",
          "./my-eslint-config.js"
        ],
        "rules": {
          "eqeqeq": "warn"
        }
      }

       

    • eslint:all,啟動所有 ESLint 內置規則,不推薦。

  • 忽略文件和目錄

    使用 .eslintignore 文件指定要忽略的文件和目錄,忽略模式的指定使用 .gitignore規范

    ESLint 默認忽略 /node_modules/*/bower_components/*

    示例:

    # /node_modules/* and /bower_components/* in the project root are ignored by default
    
    # Ignore built files except build/index.js
    build/*
    !build/index.js
    /node_modules
    node_modules
    /node_modules/*
    /dist
    dist
    /dist/*

     

     

使用 eslint-config-standard

eslint-config-standard標准風格插件

安裝

npm install eslint-config-standard

安裝相關需要的其它插件

npm install --save-dev eslint-config-standard eslint-plugin-standard eslint-plugin-promise eslint-plugin-import eslint-plugin-node

然后,將其添加到您的.eslintrc文件中:

{
  "extends": "standard"
}

 

使用 babel-eslint

babel-eslint 是一款用於 ESLint 的語法分析器,它支持使用 ESLint 分析所有 babel 兼容的代碼。

使用 babel-eslint 需要安裝 babel 並提供 babel 配置文件。

ESLint 核心規則不支持實驗階段的語法,如果要使用這部分語法,需要配合 eslint-plugin-babel 使用。

安裝

# 安裝 babel-eslint
npm install -D babel-eslint

# 安裝 eslint-plugin-babel
npm install -D eslint-plugin-babel
 

配置

{
    "parser": "babel-eslint",
    "plugins": ["babel"]
}

 

 

使用 eslint-plugin-import

 eslint-plugin-import  用於校驗es6的import規則,如果增加import plugin,在我們使用webpack的時候,如果你配置了resove.config.js的alias,那么我們希望import plugin的校驗規則會從這里取模塊的路徑,此時需要配置

“rules”: {},
"settings": {
        // 使用webpack中配置的resolve路徑
        "import/resolver": "webpack" 
}

 

 

 參考:

ESLint 使用指南

深入理解 ESLint


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM