更新時(shí)間:2022-04-13 10:49:02 來源:動(dòng)力節(jié)點(diǎn) 瀏覽3830次
大家在學(xué)習(xí)的過程中會用到很多Java開發(fā)工具,就拿js代碼格式化工具來說就有不少,eslint就是其中之一,動(dòng)力節(jié)點(diǎn)小編來給大家介紹一下eslint的使用。
直接這樣一起安裝幾個(gè)工具: npm install --save-dev husky lint-staged eslint
可以執(zhí)行./node_modules/.bin/eslint --init對當(dāng)前目錄的項(xiàng)目進(jìn)行eslint初始化,能夠通過交互式的命令進(jìn)行配置,完成后會在當(dāng)前目錄創(chuàng)建配置文件.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? # 項(xiàng)目中使用什么類型的模塊
? JavaScript modules (import/export) # vue項(xiàng)目選這個(gè)
CommonJS (require/exports)
None of these
? Which framework does your project use? # 項(xiàng)目中使用什么框架
? React
Vue.js
None of these
? Does your project use TypeScript? ? No / Yes # 項(xiàng)目是否使用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
在項(xiàng)目的package.json配置husky和lint-stage
{
"scripts": {
"prepare": "husky install", // 如果是整個(gè)項(xiàng)目統(tǒng)一用,那么只需要這樣即可
"lint-staged": "lint-staged"
},
"lint-staged": {
"src/**": [ // 可以以目錄形式指定目標(biāo)
"eslint --fix"
],
"*.{js,vue}": [ // 也可以以文件后綴的形式指定目標(biāo)
"eslint --fix"
]
}
}
如果有多個(gè)子目錄需要不同的規(guī)則可以這樣做
首先,package.json中的prepare script需要這樣改。雖然不同子目錄不同的規(guī)則,但是.git是一個(gè),所以hook也只能有一個(gè),可以在項(xiàng)目根目錄創(chuàng)建和安裝.husky
"prepare": "husky install .husky",
然后,在pre-commit腳本中添加邏輯,進(jìn)入不同的子目錄運(yùn)行不同的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
執(zhí)行npm prepare會在根目錄創(chuàng)建.husky文件夾,并將hook應(yīng)用到當(dāng)前git倉庫中
添加pre-commit hook,執(zhí)行命令./node_modules/.bin/husky add .husky/pre-commit "npm run lint-staged" && git add .husky/pre-commit
如果想要修改執(zhí)行命令可以修改.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
如果同一個(gè)倉庫里面有多個(gè)目錄需要配置單獨(dú)的規(guī)則,那么需要在每個(gè)目錄都是用eslint init一次,并在每個(gè)項(xiàng)目單獨(dú)執(zhí)行npm compare命令以安裝husky到.git 的hook中并修改每個(gè).husky/pre-commit進(jìn)入正確的目錄
eslint file.js # 校驗(yàn)指定文件
eslint --fix file.js # 校驗(yàn)并嘗試修改指定文件
全局配置
以下配置都是在.eslintrc.js中
module.exports = {
"env": { // 想啟用的環(huán)境,默認(rèn)就行
"es2021": true,
"node": true
},
"extends": [ // 從指定的插件中繼承規(guī)則
"eslint:recommended", // eslint:all表示使用eslint的所有規(guī)則,可參考http://eslint.cn/docs/rules/,"eslint:recommended"表示使用eslint所有規(guī)則里面打勾的規(guī)則,"standard"表示使用standard的規(guī)則(需要先npm install standard --save-dev),參考https://standardjs.com/rules-zhcn.html#javascript-standard-style。除了standard,還有Airbnb風(fēng)格,但我比較習(xí)慣standard
"plugin:@typescript-eslint/recommended" // 如果是typescript需要添加這個(gè)插件
],
"extends": ["standard-with-typescript"], // 如果是standard with typescript,依賴直接執(zhí)行 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代碼校驗(yàn),需安裝eslint-plugin-html
"react", // 用于react代碼的驗(yàn)證,需安裝eslint-plugin-react
],
"rules": { // 這里放自定義的規(guī)則,0表示關(guān)閉規(guī)則,1表示設(shè)置為warn,2表示error
"@typescript-eslint/strict-boolean-expressions": 0, // 禁用布爾表達(dá)式中的嚴(yán)格類型判斷,本來if(value)即使value為true或者為對象時(shí)都可以,但是如果這個(gè)規(guī)則為1,那么只能為true,必須單獨(dú)處理null或者空字符串等情況,特別麻煩
"@typescript-eslint/restrict-template-expressions": 0, // 模板語法不驗(yàn)證類型,`${abc.def}`
"@typescript-eslint/explicit-module-boundary-types": [
"error",
{ // 僅僅覆蓋規(guī)則的某個(gè)選項(xiàng)
"allowArgumentsExplicitlyTypedAsAny": true // 也可以允許typescript中使用any來聲明函數(shù)參數(shù)
}
]
"@typescript-eslint/no-explicit-any": 0, // 禁用它可以允許typescript中使用any來聲明類型
"max-len": [
"error",
{
"code": 150 // 有些規(guī)則默認(rèn)行寬只有80或者180,如果要更改該規(guī)則可以這樣做
}
],
'no-use-before-define': ['error', { variables: false, classes: false, functions: false }], // 函數(shù)或方法或類的定義在使用的后面,如果要禁用可以這樣做,一般不建議這樣做
'camelcase': 'off', // 禁用camelcase提示,不推薦禁用
'no-param-reassign': 'off', // 在函數(shù)內(nèi)修改參數(shù)的值,不推薦禁用,
'variable-name': [
true,
"allow-snake-case" // 允許下劃線分割
]
},
"overrides": [
{
files: ['pages/**'], // 如果只想要某個(gè)指定的目錄使用不同的規(guī)則,可以在overrides中這樣定義
rules: {
'react/prop-types': 'off'
}
}
]
};
指定代碼單獨(dú)/忽略配置
除了使用rules來全局忽略某些配置以外,還能在局部忽略某些配置,例如:
// eslint-disable-next-line no-undef // 能忽略下一行出現(xiàn)的未定義錯(cuò)誤,如cordova
cordova.plugins...
/* eslint-disable import/first */ // 這樣注釋能忽略當(dāng)前文件下面所有行的指定的錯(cuò)誤,這里是忽略import/first錯(cuò)誤
單獨(dú)忽略指定文件
需要在.eslintignore中添加文件,語法同.gitignore
Requires Promise-like values to be handled appropriately (no-floating-promises): Promise必須要能正確處理響應(yīng)與異常,可以加上then和catch
(async () => {
...
})() // 需要加上下面的then和catch才能避免錯(cuò)誤提示,也是一種很好的編碼習(xí)慣
.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中的一條規(guī)則no-restricted-syntax會禁用一些新特性新語法,比如for await ... in,如果要禁用不建議在rules中整個(gè)禁用,直接在使用的地方加// 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的時(shí)候仍然去檢查了node_modules里面的東西: 嘗試升級typescript到3.9.*及以上
Parameter ‘xxx’ implicitly has an ‘any’ type: 要求太嚴(yán)的話就修改tsconfig.json,將compilerOptions下的noImplicitAny設(shè)置為false
“parserOptions.project” has been set for @typescript-eslint/parser: 可以把.eslintrc.js文件加入.eslintignore中,或者把.eslintrc.js改成json后綴和格式,居然就可以了
no-plusplus: 禁止使用一元操作符++或--,是因?yàn)榭瞻卓赡軙淖冊创a的語義,可以使用+=來代替
consistent-return: 原因是函數(shù)的返回值的類型不統(tǒng)一,可以自行修改一下
react camel case props: 在react中禁止非駝峰寫法的props,如果實(shí)在改不了,可以給它重命名: {first_name: firstName, last_name: lastName}
使用git的UI客戶端,例如sourcetree,沒有觸發(fā)husky/eslint:這個(gè)一般是由于sourcetree沒有找到node導(dǎo)致,首先我們需要去sourcetree->Preference->Advanced->Always display full console output,打開后再次commit就會發(fā)現(xiàn)錯(cuò)誤日志: Can't find npx in PATH: ...Skipping pre-commit hook,找不到node路徑直接跳過了pre-commit hook。此時(shí)只需要將node路徑加入環(huán)境變量即可。一般是由于我們使用的是nvm,我們只需要將nvm路徑加入husky的環(huán)境變量即可:
vim ~/.huskyrc,這個(gè)文件就是用于加載這些環(huán)境變量的,注意這是home目錄不是項(xiàng)目目錄
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: 找不到符合條件的文件就找不到,非要抱個(gè)錯(cuò)出來,可以給eslint命令加上--no-error-on-unmatched-pattern
以上就是關(guān)于“js代碼格式化工具:eslint的使用”介紹,大家如果對此比較感興趣,想了解更多相關(guān)知識,不妨來關(guān)注一下動(dòng)力節(jié)點(diǎn)的JavaScript教程,教程中還有更豐富的知識在等著大家去學(xué)習(xí),相信會對大家有所幫助的。
初級 202925
初級 203221
初級 202629
初級 203743