給 React + TS 項目添加 ESLint + Prettier,附注意事項及文檔


ESLint 用於發現代碼錯誤,統一代碼風格。
Prettier 專門用來美化格式、統一代碼風格,在這個方面比 ESLint 更強大。

它們真的很香

本文記錄一下我給一個項目添加 ESLint + Prettier 的過程,以及遇到的問題和注意的點。

項目是 ts + react 開發的組件庫,樣式使用 scss,通過 webpack4 打包。

過程

安裝配置 ESLint

安裝需要的包

分開寫,更清晰:

npm i eslint -D
npm i @typescript-eslint/parser @typescript-eslint/eslint-plugin -D
npm i eslint-plugin-react -D
npm i eslint-config-alloy -D
npm i eslint-loader -D
  • 首先要安裝 eslint,eslint 默認使用 Espree 進行解析,無法識別 ts 的一些語法,所以需要安裝一個 ts 的解析器 @typescript-eslint/parser,用它來代替默認的解析器,然后由 @typescript-eslint/eslint-plugin 來提供有關 ts 的規則補充。
  • 由於是 react 項目,所以還需要插件 eslint-plugin-react 來支持 .tsx
  • eslint 規則眾多,且有些原生規則在 ts 中不兼容,推薦 alloy 的這套配置 eslint-config-alloy,它提供了 ts + react 的版本,並且不包含代碼格式的部分,與 Prettier 完全兼容。
  • 最后是提供給 webpack 的 eslint-loader,可以在使用 webpack-dev-server 開發中實時檢查,越早發現錯誤越好解決。

寫配置文件

接下來在項目根目錄創建 .eslintrc.json 文件

{
    "parser": "@typescript-eslint/parser",
    "plugins": [
        "@typescript-eslint/eslint-plugin"
    ],
    "extends": [
        "alloy",
        "alloy/react",
        "alloy/typescript"
    ],
    "settings": {
        "react": {
            "version": "detect"
        }
    },
    "env": {
        // 您的環境變量(包含多個預定義的全局變量)
        // Your environments (which contains several predefined global variables)
        //
        // browser: true,
        // node: true,
        // mocha: true,
        // jest: true,
        // jquery: true
    },
    "globals": {
        // 您的全局變量(設置為 false 表示它不允許被重新賦值)
        // Your global variables (setting to false means it's not allowed to be reassigned)
        //
        // myGlobal: false
    },
    "rules": {
        // 自定義您的規則
        // Customize your rules
    }
}

如上,把解析器、插件、擴展的規則集都配置進去。

添加script指令

package.jsonscripts 中添加指令,就可以使用了

// package.json

{
    "scripts": {
        "lint": "eslint '{components,example}/**/*.{ts,tsx,js,jsx}'",
        "lint_fix": "eslint '{components,example}/**/*.{ts,tsx,js,jsx}' --fix"
    }
}

以上指令表示對 componentsexample 文件夾下的 .ts .tsx .js .jsx 文件進行檢查。
上面是 glob 的形式,也可以像下面這樣寫成文件夾形式,就需要通過 --ext 來對擴展的文件類型進行指定。

// package.json

{
    "scripts": {
        "lint": "eslint {components,example} --ext .ts,.tsx,.js,jsx",
        "lint_fix": "eslint {components,example} --ext .ts,.tsx,.js,jsx --fix"
    }
}

注意:
glob 形式下文件路徑要加引號。
--ext 只能搭配文件夾形式,對 glob 形式無效。

給 webpack 添加 eslint-loader

module: {
        rules: [
            {
                test: /\.(jsx|js|ts|tsx)$/,
                include: [
                    path.resolve(__dirname, '../components'),
                    path.resolve(__dirname, '../example')
                ],
                exclude: [/node_modules/],
                use: ['eslint-loader'],
                enforce: 'pre'
            }
      ]
}

注意:
要把它放在 rules 的第一項,或者添加 enforce: 'pre' 來保證首先應用 eslint-loader,因為是要對我們的源代碼進行檢查,檢查要在 babel-loader 等其他編譯之前。

安裝 vscode 的 eslint 插件

插件中搜 eslint 直接安裝,就可以在編輯器擁有實時錯誤標紅。
然后在 settings.json 中添加:

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

就可以在保存文件時自動 fix。

怎么打開 settings.json ?左下角齒輪 -> 第一行 command ... -> 輸入 open settings.json

添加 .eslintignore 文件

編輯器中的檢測沒有指定路徑,所以會檢查 componentsexample 之外的文件,如果有些不想讓它檢查,可以根目錄添加 .eslintignore 文件。

build/
dist/

默認包含 node_modules/

ESLint 就配置好了,包括 配置文件 + 執行腳本 + webpack + 編輯器。

安裝配置 Prettier

安裝 Prettier 包

npm i prettier -D

新建 prettier.config.js 文件配置規則

prettier 的配置規則很少,推薦一套作為參考。

// prettier.config.js or .prettierrc.js
module.exports = {
    // 一行最多 100 字符
    printWidth: 100,
    // 使用 4 個空格縮進
    tabWidth: 4,
    // 不使用縮進符,而使用空格
    useTabs: false,
    // 行尾需要有分號
    semi: true,
    // 使用單引號
    singleQuote: true,
    // 對象的 key 僅在必要時用引號
    quoteProps: 'as-needed',
    // jsx 不使用單引號,而使用雙引號
    jsxSingleQuote: false,
    // 末尾不需要逗號
    trailingComma: 'none',
    // 大括號內的首尾需要空格
    bracketSpacing: true,
    // jsx 標簽的反尖括號需要換行
    jsxBracketSameLine: false,
    // 箭頭函數,只有一個參數的時候,也需要括號
    arrowParens: 'always',
    // 每個文件格式化的范圍是文件的全部內容
    rangeStart: 0,
    rangeEnd: Infinity,
    // 不需要寫文件開頭的 @prettier
    requirePragma: false,
    // 不需要自動在文件開頭插入 @prettier
    insertPragma: false,
    // 使用默認的折行標准
    proseWrap: 'preserve',
    // 根據顯示樣式決定 html 要不要折行
    htmlWhitespaceSensitivity: 'css',
    // 換行符使用 lf
    endOfLine: 'lf'
};

執行檢查

npx prettier --test .  // 全部文件
npx prettier --test components/  // 特定文件

執行修復

npx prettier --write .  // 全部文件
npx prettier --write components/  // 特定文件

安裝 vscode 的插件,自動格式化

實際上不用執行,直接安裝編輯器插件,保存文件就直接自動格式化了。
vscode 搜 prettier 直接安裝,然后在 settings.json 中添加配置:

"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode"

遇到的問題

1.eslint 匹配不到文件會報錯

剛開始 eslint 總是會報錯

Oops! Something went wrong! 😦

ESLint: 7.5.0

No files matching the pattern "node_modules/asn1.js" were found.
Please check for typing mistakes in the pattern.

然后發現是因為沒有匹配到文件,就報錯了。。
可以添加 flag --no-error-on-unmatched-pattern 禁止這種報錯。

2.tsllint 已棄用

tslint 已經於2019年1月就不再維護,並提供到 typescript-eslint 的遷移,可以說 typescript-eslint 是目前支持 ts 的首選 lint。

3.prettier 不支持縮進語法的 css 預編譯語言

prettier 支持非常多的文件類型,目前為止官網支持的文件如下

  • JavaScript (including experimental features)
  • JSX
  • Angular
  • Vue
  • Flow
  • TypeScript
  • CSS, Less, and SCSS
  • HTML
  • JSON
  • GraphQL
  • Markdown, including GFM and MDX
  • YAML

要注意的是,對於樣式它和 stylelint 一樣,不支持縮進格式風格的.sass.styl

最后附上文檔地址

eslint rules: https://eslint.org/docs/rules/
eslint rules 中文: http://eslint.cn/docs/rules/

typescript-eslint rules

prettier 文檔: https://prettier.io/docs/en/index.html

typescript代碼檢查: https://ts.xcatliu.com/engineering/lint.html


免責聲明!

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



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