更新時間:2022-04-13 10:49:02 來源:動力節點 瀏覽3722次
大家在學習的過程中會用到很多Java開發工具,就拿js代碼格式化工具來說就有不少,eslint就是其中之一,動力節點小編來給大家介紹一下eslint的使用。
直接這樣一起安裝幾個工具: npm install --save-dev husky lint-staged eslint
可以執行./node_modules/.bin/eslint --init對當前目錄的項目進行eslint初始化,能夠通過交互式的命令進行配置,完成后會在當前目錄創建配置文件.eslintrc.js
? 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
? What type of modules does your project use? # 項目中使用什么類型的模塊
? JavaScript modules (import/export) # vue項目選這個
CommonJS (require/exports)
None of these
? Which framework does your project use? # 項目中使用什么框架
? React
Vue.js
None of these
? Does your project use TypeScript? ? No / Yes # 項目是否使用TypeScript,如果是下面會提示是否安裝typescript的eslint
? Where does your code run? … (Press <space> to select, <a> to toggle all, <i> to invert selection)
? Browser
? Node
? What format do you want your config file to be in? …
? JavaScript
YAML
JSON
@typescript-eslint/eslint-plugin@latest @typescript-eslint/parser@latest
? Would you like to install them now with npm? ? No / Yes
在項目的package.json配置husky和lint-stage
{
"scripts": {
"prepare": "husky install", // 如果是整個項目統一用,那么只需要這樣即可
"lint-staged": "lint-staged"
},
"lint-staged": {
"src/**": [ // 可以以目錄形式指定目標
"eslint --fix"
],
"*.{js,vue}": [ // 也可以以文件后綴的形式指定目標
"eslint --fix"
]
}
}
如果有多個子目錄需要不同的規則可以這樣做
首先,package.json中的prepare script需要這樣改。雖然不同子目錄不同的規則,但是.git是一個,所以hook也只能有一個,可以在項目根目錄創建和安裝.husky
"prepare": "husky install .husky",
然后,在pre-commit腳本中添加邏輯,進入不同的子目錄運行不同的eslint程序
!/bin/sh
. "$(dirname "$0")/_/husky.sh"
cd frontend
echo 'Check frontend code'
if [ -f "node_modules/.bin/lint-staged" ]; then
./node_modules/.bin/lint-staged
else
lint-staged
fi
cd ../backend
echo 'Check Backend code'
if [ -f "node_modules/.bin/lint-staged" ]; then
./node_modules/.bin/lint-staged
else
lint-staged
fi
執行npm prepare會在根目錄創建.husky文件夾,并將hook應用到當前git倉庫中
添加pre-commit hook,執行命令./node_modules/.bin/husky add .husky/pre-commit "npm run lint-staged" && git add .husky/pre-commit
如果想要修改執行命令可以修改.husky/pre-commit例如
!/bin/sh
. "$(dirname "$0")/_/husky.sh"
cd myDir
echo 'Check My code'
if [ -f "node_modules/.bin/lint-staged" ]; then
./node_modules/.bin/lint-staged
else
lint-staged
fi
如果同一個倉庫里面有多個目錄需要配置單獨的規則,那么需要在每個目錄都是用eslint init一次,并在每個項目單獨執行npm compare命令以安裝husky到.git 的hook中并修改每個.husky/pre-commit進入正確的目錄
eslint file.js # 校驗指定文件
eslint --fix file.js # 校驗并嘗試修改指定文件
全局配置
以下配置都是在.eslintrc.js中
module.exports = {
"env": { // 想啟用的環境,默認就行
"es2021": true,
"node": true
},
"extends": [ // 從指定的插件中繼承規則
"eslint:recommended", // eslint:all表示使用eslint的所有規則,可參考http://eslint.cn/docs/rules/,"eslint:recommended"表示使用eslint所有規則里面打勾的規則,"standard"表示使用standard的規則(需要先npm install standard --save-dev),參考https://standardjs.com/rules-zhcn.html#javascript-standard-style。除了standard,還有Airbnb風格,但我比較習慣standard
"plugin:@typescript-eslint/recommended" // 如果是typescript需要添加這個插件
],
"extends": ["standard-with-typescript"], // 如果是standard with typescript,依賴直接執行 npm install --save-dev eslint-config-standard-with-typescript,npm<7需要參考https://github.com/standard/eslint-config-standard-with-typescript
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 12,
"sourceType": "module"
},
"plugins": [ // 使用的額外的插件,例如下面的html插件和react插件
"@typescript-eslint",
"html", // 用于html代碼中的js代碼校驗,需安裝eslint-plugin-html
"react", // 用于react代碼的驗證,需安裝eslint-plugin-react
],
"rules": { // 這里放自定義的規則,0表示關閉規則,1表示設置為warn,2表示error
"@typescript-eslint/strict-boolean-expressions": 0, // 禁用布爾表達式中的嚴格類型判斷,本來if(value)即使value為true或者為對象時都可以,但是如果這個規則為1,那么只能為true,必須單獨處理null或者空字符串等情況,特別麻煩
"@typescript-eslint/restrict-template-expressions": 0, // 模板語法不驗證類型,`${abc.def}`
"@typescript-eslint/explicit-module-boundary-types": [
"error",
{ // 僅僅覆蓋規則的某個選項
"allowArgumentsExplicitlyTypedAsAny": true // 也可以允許typescript中使用any來聲明函數參數
}
]
"@typescript-eslint/no-explicit-any": 0, // 禁用它可以允許typescript中使用any來聲明類型
"max-len": [
"error",
{
"code": 150 // 有些規則默認行寬只有80或者180,如果要更改該規則可以這樣做
}
],
'no-use-before-define': ['error', { variables: false, classes: false, functions: false }], // 函數或方法或類的定義在使用的后面,如果要禁用可以這樣做,一般不建議這樣做
'camelcase': 'off', // 禁用camelcase提示,不推薦禁用
'no-param-reassign': 'off', // 在函數內修改參數的值,不推薦禁用,
'variable-name': [
true,
"allow-snake-case" // 允許下劃線分割
]
},
"overrides": [
{
files: ['pages/**'], // 如果只想要某個指定的目錄使用不同的規則,可以在overrides中這樣定義
rules: {
'react/prop-types': 'off'
}
}
]
};
指定代碼單獨/忽略配置
除了使用rules來全局忽略某些配置以外,還能在局部忽略某些配置,例如:
// eslint-disable-next-line no-undef // 能忽略下一行出現的未定義錯誤,如cordova
cordova.plugins...
/* eslint-disable import/first */ // 這樣注釋能忽略當前文件下面所有行的指定的錯誤,這里是忽略import/first錯誤
單獨忽略指定文件
需要在.eslintignore中添加文件,語法同.gitignore
Requires Promise-like values to be handled appropriately (no-floating-promises): Promise必須要能正確處理響應與異常,可以加上then和catch
(async () => {
...
})() // 需要加上下面的then和catch才能避免錯誤提示,也是一種很好的編碼習慣
.then(() => { console.log('Start Success') })
.catch(() => { console.log('Start Failed') })
Require statement not part of import statement. 引入包的方式不同,需要將包引入方式改為允許的方式,例如
將const path = require('path')改為import path = require('path')
ESLint: iterators/generators require regenerator-runtime, which is too heavyweight for this guide to allow them. Separately, loops should be avoided in favor of array iterations.(no-restricted-syntax): 這是Airbnb中的一條規則no-restricted-syntax會禁用一些新特性新語法,比如for await ... in,如果要禁用不建議在rules中整個禁用,直接在使用的地方加// eslint-disable-next-line no-restricted-syntax吧
lint-staged Node.js requirement to 12.13.0: 最新版本的lint-staged要求node版本>=12.13.0(21年的),或者降級lint-staged
eslint.rc里面的excludes不起作用,tsc的時候仍然去檢查了node_modules里面的東西: 嘗試升級typescript到3.9.*及以上
Parameter ‘xxx’ implicitly has an ‘any’ type: 要求太嚴的話就修改tsconfig.json,將compilerOptions下的noImplicitAny設置為false
“parserOptions.project” has been set for @typescript-eslint/parser: 可以把.eslintrc.js文件加入.eslintignore中,或者把.eslintrc.js改成json后綴和格式,居然就可以了
no-plusplus: 禁止使用一元操作符++或--,是因為空白可能會改變源代碼的語義,可以使用+=來代替
consistent-return: 原因是函數的返回值的類型不統一,可以自行修改一下
react camel case props: 在react中禁止非駝峰寫法的props,如果實在改不了,可以給它重命名: {first_name: firstName, last_name: lastName}
使用git的UI客戶端,例如sourcetree,沒有觸發husky/eslint:這個一般是由于sourcetree沒有找到node導致,首先我們需要去sourcetree->Preference->Advanced->Always display full console output,打開后再次commit就會發現錯誤日志: Can't find npx in PATH: ...Skipping pre-commit hook,找不到node路徑直接跳過了pre-commit hook。此時只需要將node路徑加入環境變量即可。一般是由于我們使用的是nvm,我們只需要將nvm路徑加入husky的環境變量即可:
vim ~/.huskyrc,這個文件就是用于加載這些環境變量的,注意這是home目錄不是項目目錄
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
export PATH="/Users/haofly/.nvm/versions/node/v15.3.0/bin:$PATH" # 上面的配置還是不行那直接加到PATH吧
No files matching the pattern "" were found: 找不到符合條件的文件就找不到,非要抱個錯出來,可以給eslint命令加上--no-error-on-unmatched-pattern
以上就是關于“js代碼格式化工具:eslint的使用”介紹,大家如果對此比較感興趣,想了解更多相關知識,不妨來關注一下動力節點的JavaScript教程,教程中還有更豐富的知識在等著大家去學習,相信會對大家有所幫助的。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習