最初釋出于 szhshp的第三邊境研究所, 轉載請注明
ESlint: 常見問題解答
Global or Locally?
除非你能夠保證所有項目都使用相同的配置, 否則建議本地安裝.
并且建議 永遠不要全局安裝 ESlint, 你會被不同項目的版本問題搞得生不如死
本地安裝方法
首先跑到 D:\NodeJS\node_global 裡面把之前全局安裝的 ESlint 的包全部給删除掉.
然後跑到項目檔案夾:
cnpm i eslint --save-dev
複制
然後本地 bash 裡面 init 一下:
./node_modules/.bin/eslint --init
# Windows 下為反斜杠
.\node_modules\.bin\eslint --init
複制
然後他會指導你安裝對應的包
可以讓他幫忙安裝或者點選取消自己用 npm/yarn 安裝
最好一個一個安裝并且安裝的時候選擇他标示的最高版本
比如:
這裡我們肯定就直接用7.20的。
eslint@^5.16.0 || ^6.8.0 || ^7.2.0
Checking peerDependencies of eslint-config-google@latest
The config that you've selected requires the following dependencies:
eslint-plugin-vue@latest eslint-config-google@latest eslint@>=5.16.0
? Would you like to install them now with npm? No <-- 我這裡選擇了 No
Successfully created .eslintrc.json file in G:\Dev\GitRepos\Github\ToooooooLooooongDoNotRead
複制
本地安裝之後依然無法使用
考慮一下是否是後期額外添加了 ESLint, 遇到這種情況, 一般把整個
node_modules
删掉然後重新 cnpm i 即可
某些依賴無法找到
有可能安裝後還會缺少一些包, 本地對應一個檔案執行一下試一下:
$ ./node_modules/.bin/eslint main.js
# Windows 下變成了反斜杠
$ .\node_modules\.bin\eslint hooks\recentComments.ts
複制
裡面就會告訴你有哪些包沒有找到, 将這些包也本地安裝一下就好了.
ESLint couldn't find the config "airbnb" to extend from. Please check that the name of the config is correct.
cnpm i eslint@^6.1.0 eslint-config-airbnb eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react
複制
然後同樣本地運作一次
$ ./node_modules/.bin/eslint main.js
複制
試一下行不行, 如果可以就重新跑一次
--save-dev
儲存到
package.json
ESLint: Jest - test not found
隻要在配置檔案
.eslintrc.json
裡面加一兩行就可以:
{
"env": {
"jest": true
},
}
複制
ESLint - VSC 不顯示
最近修改了 Node 版本, 路徑也改了, 就出現了一些問題
主要的解決方法:
檢查 VSC 的 ESLint 裡面的設定, 直接編輯設定檔案:
主要确認以下兩個配置
"eslint.nodePath": "C:/InstalledSoftware/NodeJS12/node.exe",
"eslint.validate": ["javascript", "javascriptreact", "typescript", "typescriptreact", "html", "vue"]
複制
ESLint 內建 Husky Precommit
先配置好 Eslint, 所有必要的元件安裝好, 并且保證 ESLint 可以跑: ./node_modules/.bin/eslint xxx.js
npm i -D husky lint-staged
npx mrm lint-staged
# 如果不跑一次 rebuild 可能無效, 另外重裝 node_modules 也可以
npm rebuild
複制
Usage
忽略特定檔案或檔案夾
根目錄建立一個檔案
.eslintignore
:
/out
/.next
複制
檢查多個不同擴充名
.\node_modules\.bin\eslint --ext .tsx,.ts .
複制
使用 npm run check
執行 ESlint
npm run check
"lint": "eslint . --ext .tsx,.ts --fix", /* 檢查并修複 */
"lint-error": "eslint . --ext .tsx,.ts --fix --quite", /* 隻對 Error 進行檢查并修複 */
"check": "eslint . --ext .tsx,.ts", /* 僅僅檢查 */
"check-error": "eslint . --ext .tsx,.ts --quite" /* 隻對 Error 進行檢查 */
複制