沉冰浮水

沉冰浮水

做最终到的事,成为最终成为的人!
github
bilibili
mastodon
zhihu
douban

「折騰」ESLint 安裝與使用

寫在前邊#

因為嫌麻煩,並沒有實際用到過 ESLint;

最近改了個別人寫的東西,別的不說,單行註釋雙斜線後不加空格實在是逼死強迫症。

資源網址#

ESLint - Visual Studio Marketplace:

https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint

ESLint - Pluggable JavaScript linter - ESLint 中文:

http://eslint.cn/

雖然不太清楚,使用 VSCode 插件版仍然需要在項目下或全局安裝eslint的樣子?

安裝 ESLint#

# 安裝 cnpm
npm install -g cnpm --registry=https://registry.npmmirror.com

使用 cnpm 沉冰浮水 仍然搜索不到匹配,/ 哭;

全局安裝:

# 全局安裝
cnpm install -g eslint
# 查看版本號
cnpm ls eslint
# 不知道為什麼輸出為空,加 -g 參數則直接卡住
# 也沒找到正確能用的方法

# 下邊命令可以得到全局 node_modules 的地址
cnpm root -g

當前項目內:

# 當前項目內
cnpm install eslint --save-dev
# 查看版本號
cnpm ls eslint

初始化#

cnpm init @eslint/config
# pnpm create @eslint/config
# eslint --init
# 所在目錄如果沒有 package.json 可能會報錯,`npm init` 創建;

# 選項一 - 如何使用 ESLint
? How would you like to use ESLint?
  To check syntax only
 To check syntax and find problems
  To check syntax, find problems, and enforce code style
# 注:如果選擇了第 3 項,後續選項會不一樣


# 選項二 - 模塊引入方式
? What type of modules does your project use?
 JavaScript modules (import/export)
  CommonJS (require/exports)
  None of these

# 選項三 - 項目使用的框架
? Which framework does your project use?
  React
 Vue.js
  None of these

# 選項四 - 是否使用 TypeScript
? Does your project use TypeScript? ‣ No / Yes

# 選項五 - 項目使用的環境,可以都選或都不選
? Where does your code run? …  (Press <space> to select, <a> to toggle all, <i> to invert selection)
 Browser
 Node

# 選項六 - ESLint Config 文件保存为何種格式,建議 JS,JSON 不支持註釋
? What format do you want your config file to be in?
 JavaScript
  YAML
  JSON

# 選項七 - 根據選擇可能需要安裝額外的項目,比如 vue 的插件
The config that you ve selected requires the following dependencies:

eslint-plugin-vue@latest

# 選項七 - 是否直接安裝上邊列出的項目
? Would you like to install them now? ‣ No / Yes

# 選項八 - 如果上一步選擇了安裝,會詢問使用的包管理器
? Which package manager do you want to use?
  npm
  yarn
 pnpm

# ------------

# 如果上邊「選項一」選擇了「To check syntax, find problems, and enforce code style」,會多出以下選項
? How would you like to define a style for your project?
  Use a popular style guide
 Answer questions about your style

# 分支二 - 詢問具體的代碼風格,包括縮進、引號、分號等
 How would you like to define a style for your project? · prompt
 What style of indentation do you use? · 4
 What quotes do you use for strings? · double
 What line endings do you use? · unix
 Do you require semicolons? · No / Yes

# 分支一 - 選擇 google 等廠商的代碼風格
 How would you like to define a style for your project? · guide
 Which style guide do you want to follow? · google

選項一:

  • 僅檢查語法;
  • 檢查語法並查找問題;
  • 在前者基礎上強制代碼樣式;

默認為第 2 項,實際建議第 3 項;

之後根據實際需要用;

額外注意:

  • 配置文件建議使用 JS 格式,因為 JSON 不支持註釋;
  • 本文是以 cnpm 為基礎,包管理器選項裡沒有,可以換 pnpm;
  • 或者不選擇自動安裝,手動執行cnpm install

使用(CLI)#

# 檢查指定文件
eslint vite.config.js

# 可以使用 --fix 修復能夠自動修復的問題

# 按路徑匹配文件,某一對引號內的規則沒能匹配到文件時會報錯
eslint "src/**/*.vue" "src/**/*.{js,mjs,ts}" --fix

# 指定後綴,注意後綴前的點號,也不需要加空格,不需要每種後綴都有相應的文件
eslint . --ext .js,.ts,.mjs --fix

# 排除指定文件中定義的路徑
eslint . --ext .js,.ts,.mjs --fix --ignore-path .gitignore

Command Line Interface - ESLint 中文:

http://eslint.cn/docs/user-guide/command-line-interface

VSCode 插件版#

注:插件版本好像依賴於全局安裝的eslint包?

在「命令面板(Ctrl + Shift + P)」中輸入eslint即可查看所擁有的命令:

  • ESLint: Create ESLint configuration 創建配置文件;
  • ESLint: Fix all auto-fixable Problems 修復能夠自動修復的問題;
  • ESLint: Migrate Settings 遷移設置,啥用暫不清楚;
  • ESLint: Show Output Channel 查看日誌輸出,從信息看確實依賴於node_modules\eslint\lib\api.js
  • ESLint: Restart ESLint Server 重啟插件服務;

因為 VSCode 默認終端是 Git Bash,所以自動觸發創建命令時出現了下邊錯誤:

node_modules\.bin\eslint.cmd --init
# bash: node_modules.bineslint.cmd: command not found

所以保險起見還是自己執行cnpm init @eslint/config吧;

插件有不少配置項,可以在「設置」中搜索eslint查看:

{
  "eslint.validate": [
    "typescript",
    "javascript",
    "javascriptreact",
    "vue"
  ],
  // 這裡甚至並不能用「cnpm」 - -!
  "eslint.packageManager": "pnpm"
}

檢查規則#

使用 @eslint/config 初始化,然後再修改具體細節,下邊為一份參考:

/* // global module // 好像新版不需要設置這個了? */
module.exports = {
    'env': {
        'browser': true,
        'es2021': true,
    },
    'extends': 'eslint:recommended',
    'parserOptions': {
        'ecmaVersion': 'latest',
    },
    // 全局變量聲明
    'globals': {
        'module': 'readonly',
        'require': 'readonly',
    },
    // 規則定義
    'rules': {
        /* 相對通用的規則 */

        // 縮進
        'indent': [
            'error',
            4,
        ],
        // 換行符
        'linebreak-style': [
            'error',
            'unix',
        ],
        // 引號
        'quotes': [
            'error',
            'single',
        ],
        // 分號
        'semi': [
            'error',
            'never',
        ],
        // 單行註釋的空格
        'spaced-comment': [
            'error',
            'always',
        ],

        /* 以下按需配置 */

        // // 允許 require 語法賦值
        // '@typescript-eslint/no-var-requires': 0,

        // // generator 函數中 * 號前後的空格
        // 'generator-star-spacing': 0,

        // 對象或數組的拖尾逗號
        // always-multiline 表示只有在多行時才需要拖尾逗號
        'comma-dangle': [
            1,
            'always-multiline',
        ],

        // 箭頭函數參數括號
        // as-needed 表示只有在需要時才添加括號
        'arrow-parens': [
            1,
            'as-needed',
            { 'requireForBlockBody': true },
        ],

        // 變量聲明後未使用
        // args: "none" 表示不檢查函數參數是否被使用
        'no-unused-vars': [
            1,
            { 'args': 'none' },
        ],

        // 函數圓括號之前的空格
        // anonymous: "never" 表示匿名函數不允許空格
        // named: "never" 表示命名函數不允許空格
        'space-before-function-paren': [
            1,
            { 'anonymous': 'never', 'named': 'never' },
        ],

        // 禁止不規則的空白
        'no-irregular-whitespace': [
            2,
            { 'skipStrings': true, 'skipRegExps': true },
        ],

        // // 正式環境禁止 debugger
        // 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0,
    },
}

List of available rules - ESLint 中文:

http://eslint.cn/docs/rules/

錯誤排查#

1、

Environment key "es2021" is unknown

項目中已經安裝 ESLint 但是版本太低,請刪除「package-lock.json」文件後重新執行cnpm install eslint --save-devcnpm install eslint@latest --save-dev

仍然有問題請刪除 node_modules 後再試;

可在「本站(www.wdssmq.com)」搜索關鍵詞:快速刪除 node_modules快速刪除

2、

Parsing error: Invalid ecmaVersion.

默認生成的配置文件中有一項是"ecmaVersion": 12,,改成 11 或 10,雖然並不清楚有啥用;

3、

Do not access Object.prototype method 'hasOwnProperty' from target object.eslintno-prototype-builtins

出於安全並不建議直接用:foo.hasOwnProperty("bar"),而應該寫成 Object.prototype.hasOwnProperty.call(foo, "bar")

正則替換:

([a-z0-9]+)\.hasOwnProperty\(([^\)]+)\)

Object.prototype.hasOwnProperty.call($1, $2)

然後 VSCode 中 forin 的代碼片段如下,看了已經修改過了:

for (const key in object) {
  if (Object.hasOwnProperty.call(object, key)) {
    const element = object[key];

  }
}

4、

The "marketId" property should be a constructor.eslintvue/require-prop-type-constructor

vue 中定義props對像時,多個類型聲明應寫為數組;

export default {
    props: {
        myProp1: Number | String, // 錯誤
        myProp2: [Number, String] // 正確
    }
}

5、

'__dirname' is not defined.eslintno-undef

錯誤提示出現在「vite.config.js」中;

解決:

.eslintrc.json 或其他格式的配置文件中,確保對應聲明中存在"node": true,這一項;

{
  "env": {
    "browser": true,
    "node": true,
    "es2021": true
  }
}

6、

The template root requires exactly one element.eslintvue/no-multiple-template-root

報錯代碼如下,將<template> ** </template>改為<template><div> ** </div></template>可以消除這個錯誤,但是不太科學;

<template>
  <Header class="header" />
  <router-view class="content" />
  <Footer class="footer" />
</template>

正確方法,修改「.eslintrc.json」文件

"extends": ["eslint:recommended", "plugin:vue/essential"],"extends": ["eslint:recommended", "plugin:vue/vue3-essential"],

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。