變成rule的形狀(2) - ESLint


Posted by TempuraEngineer on 2022-05-29

ESLint

一個Javascript coding style的檢查工具(linter),有被整合在vue cli裡。目前有3大標準-standard、Airbnb、Google

設定檔為.eslintrc.js(本文中的例子),也可以是.json、.yaml。放在根目錄下


2個最盛行的標準

敘述 ESLint rule standard Airbnb
原則 整齊就行 嚴格
變數命名 camelcase camel case、pascal case(class、constructor) camel case(一般)、pascal case(class、constructor)
縮排 indentation 2 space 2 space
引號 quote single quote single quote
句尾分號 semicolons
分號後 semi-spacing 1 space -
逗號後 comma-spacing 1 space 1 space
物件內最後一個屬性尾逗點 comma-dangle
私有屬性 no-underscore-dangle - _開頭
複製陣列 - 用展開運算子
關鍵字後 keyword-spacing 1 space 1 space
函式括號前 space-before-function-paren 1 space 1 space
method chaining - 要斷行、縮排
程式區塊前 space-before-blocks 1 space 1 space
程式區塊內 block-spacing 1/1 space 1/1 space
程式區塊內壓空行 padded-blocks
比較運算子 eqeqeq 多用嚴格對比 多用嚴格對比
中綴運算子前後 space-infix-ops 1/1 space 1/1 space
運算子斷行 operator-linebreak 賦值時若要斷行,用()包住值。三元運算子多行時,條件一行,?與後面的敘述各一行 三元運算子盡量單行,多行時,條件一行,?與後面的敘述各一行
物件key後 key-spacing 1 space 1 space
避免重複import同module no-duplicate-imports
「import * as xxx」引入 wildcard import -
多行import object-curly-newline - 斷行
export命名 - camel case命名,但若是空物件、lib則為pascal case。export名要和檔名相同
框架 React常用


建立設定檔

  • vue cli
    vue cli設定linter
    如果用vue cli開專案的話,手動設定,然後選擇其中一個linter與formatter的組合

    如果要在儲存時auto fix就選lint on save,完成所有設定就會自動生成.eslintrc.js

    透過這個方式建立的好處是簡單

  • 手動指令建立

    手動設定linter

      npm init @eslint/config
    

    自訂linter的style
    透過指令建立的好處是自由,因為"define style"這一問可以選"answer question"來自訂


.eslintrc.js的屬性們

env

運行環境

env:{ // 在Node和瀏覽器執行則都設true
  node:true,
  browser:true,
}


extends

  • @vue/eslint-config-typescript
    用於Vue的Typescript的config

    This config is specifically designed to be used by @vue/cli & create-vue setups and is not meant for outside use (it can be used but some adaptations on the user side might be needed - for details see the config file).

    以下是上文翻譯

    這個config是設計給用vue cli建立的專案,並不適合單獨使用 (它可以被使用,只是客戶端或許會需要額外的adaption,詳細查看config file)

    它底下除了其自身的rule,還有@vue/eslint-config-typescript/recommended的rule(可自行決定要不要用)


plugin

  • eslint-plugin-vue
    官方的ESLint plugin,可用來檢查.vue的template、script,和.js裡的Vue code,ESLint v6.2.0以下Node.js v16.x以下(除了v14.7.x)無法使用

    分成4種規範-"plugin:vue/base"(最鬆), "plugin:vue/essential", "plugin:vue/strongly-recommended", "plugin:vue/recommended"(最嚴)

    如果使用Vue 3的話則是在vue/後面加vue3-(ex: "plugin:vue/vue3-base")

  • eslint-plugin-import
    檢查import/export語法、路徑有無錯誤、export名有沒有跟import名相同...等

    如果是Typescript專案還需要安裝@typescript-eslint/parsereslint-import-resolver-typescript


rules

ESLint會根據extends、rules去檢查。
rules可以在ESLint rulesavailable rules查詢


ignorePatterns

定義不想被ESLint檢查的檔案,預設會有node_modules、bower_components

{
  "ignorePatterns": ["temp.js", "**/vendor/*.js"],
}

如果glob pattern以/開頭的話,路徑會相對於.eslintrc.js所在的根目錄。例如:.eslintrc.json在lib底下(lib/.eslintrc.json),pattern 寫/foo.js則會去抓lib/foo.js,而不會抓lib/subdir/foo.js.

如果除了根目錄的.eslintrc.js,還有configs/.eslintrc.js,那在configs這個資料夾中configs/.eslintrc.js將會有優先權。

此外configs/.eslintrc.js裡ignorePattern的pattern以/開頭的話,路徑將相對於configs/.eslintrc.js,而非根目錄的.eslintrc.js

If a glob pattern starts with /, the pattern is relative to the base directory of the config file. For example, /foo.js in lib/.eslintrc.json matches to lib/foo.js but not lib/subdir/foo.js.

If a config is provided via the --config CLI option, the ignore patterns that start with / in the config are relative to the current working directory rather than the base directory of the given config. For example, if --config configs/.eslintrc.json is present, the ignore patterns in the config are relative to . rather than ./configs.

If .eslintrc. and/or package.json files are also used for configuration (i.e., --no-eslintrc was not specified), the configurations will be merged. Options from this configuration file have precedence over the options from .eslintrc. and package.json files.

另外也可以用.eslintignore來設定。當.eslintignore和.eslintrc.js裡的ignorePattern同時存在時,前者會比較`優先


檢查

ESLint錯誤提示
有裝ESLint的話有,error或waring都會被畫線,只要滑到畫線處會出現提示

如果用vue cli開專案的話,會直接裝好@vue/cli-plugin-eslint,package.json的script也會有檢查的指令

"scripts": {
  "lint": "vue-cli-service lint"
},

如果script沒有lint也可以用指令檢查

eslint "src/**/*.{js,vue}"


自動排版(Automatically fix)

修改不符合extends、rules的語法

  • 手動指令修改

    // Automatically fix problems
    npx eslint --fix "src/**/*.{js,vue}"
    
    // Automatically fix problems without saving the changes to the file system
    npx eslint --fix --fix-dry-run "src/**/*.{js,vue}"
    
    // Specify the types of fixes to apply (directive, problem, suggestion, layout)
    npx eslint --fix --fix-type suggestion "src/**/*.{js,vue}"
    
  • 儲存時自動修改
    修改vs code的setting.json

    "editor.codeActionsOnSave": {
        "source.fixAll.eslint": true,
    }
    

    另外雖然ESLint官網提到「配合vs code的extension ESLint使用的話要加"eslint.validate"」,但其實vs code v2.0.4開始,如果是要偵測.js、.ts、.vue、.html不必再設定了

    eslint.validate - an array of language identifiers specifying the files for which validation is to be enforced. This is an old legacy setting and should in normal cases not be necessary anymore. Defaults to ["javascript", "javascriptreact"].

    Improved TypeScript detection - As soon as TypeScript is correctly configured inside ESLint, you no longer need additional configuration through VS Code's eslint.validate setting. The same is true for HTML and Vue.js files.

    setting.json的屬性各有什麼用途可以看Default settings


📖

Configuring ESLint
ESLint Rules
透過 ESLint 學習 JavaScript ES6

JavaScript Standard Style

Airbnb JavaScript Style Guide
Airbnb JavaScript Style Guide - 中文版

ESLint - plugin-vue

VS Code extension - ESLint


#ESLint #linter







Related Posts

Web Storage2: HTTP, Session & Cookie

Web Storage2: HTTP, Session & Cookie

七天打造自己的 Google Map 應用入門 - Day04

七天打造自己的 Google Map 應用入門 - Day04

MTR04_0916

MTR04_0916


Comments