ESLint 用于發(fā)現(xiàn)代碼錯(cuò)誤,統(tǒng)一代碼風(fēng)格。
Prettier 專門用來美化格式、統(tǒng)一代碼風(fēng)格,在這個(gè)方面比 ESLint 更強(qiáng)大。
本文記錄一下我給一個(gè)項(xiàng)目添加 ESLint + Prettier 的過程,以及遇到的問題和注意的點(diǎn)。
項(xiàng)目是 ts + react 開發(fā)的組件庫,樣式使用 scss,通過 webpack4 打包。
過程
一、安裝配置 ESLint
1. 安裝需要的包
分開寫,更清晰:
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 默認(rèn)使用
Espree進(jìn)行解析,無法識別 ts 的一些語法,所以需要安裝一個(gè) ts 的解析器@typescript-eslint/parser,用它來代替默認(rèn)的解析器,然后由@typescript-eslint/eslint-plugin來提供有關(guān) ts 的規(guī)則補(bǔ)充。 - 由于是 react 項(xiàng)目,所以還需要插件
eslint-plugin-react來支持.tsx。 - eslint 規(guī)則眾多,且有些原生規(guī)則在 ts 中不兼容,推薦 alloy 的這套配置
eslint-config-alloy,它提供了 ts + react 的版本,并且不包含代碼格式的部分,與 Prettier 完全兼容。 - 最后是提供給 webpack 的
eslint-loader,可以在使用webpack-dev-server開發(fā)中實(shí)時(shí)檢查,越早發(fā)現(xiàn)錯(cuò)誤越好解決。
2. 寫配置文件
接下來在項(xiàng)目根目錄創(chuàng)建 .eslintrc.json 文件
{
"parser": "@typescript-eslint/parser",
"plugins": [
"@typescript-eslint/eslint-plugin"
],
"extends": [
"alloy",
"alloy/react",
"alloy/typescript"
],
"settings": {
"react": {
"version": "detect"
}
},
"env": {
// 您的環(huán)境變量(包含多個(gè)預(yù)定義的全局變量)
// Your environments (which contains several predefined global variables)
//
// browser: true,
// node: true,
// mocha: true,
// jest: true,
// jquery: true
},
"globals": {
// 您的全局變量(設(shè)置為 false 表示它不允許被重新賦值)
// Your global variables (setting to false means it's not allowed to be reassigned)
//
// myGlobal: false
},
"rules": {
// 自定義您的規(guī)則
// Customize your rules
}
}
如上,把解析器、插件、擴(kuò)展的規(guī)則集都配置進(jìn)去。
3. 添加script指令
在 package.json 的 scripts 中添加指令,就可以使用了
// package.json
{
"scripts": {
"lint": "eslint '{components,example}/**/*.{ts,tsx,js,jsx}'",
"lint_fix": "eslint '{components,example}/**/*.{ts,tsx,js,jsx}' --fix"
}
}
以上指令表示對 components 和 example 文件夾下的 .ts .tsx .js .jsx 文件進(jìn)行檢查。
上面是 glob 的形式,也可以像下面這樣寫成文件夾形式,就需要通過 --ext 來對擴(kuò)展的文件類型進(jìn)行指定。
// 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 形式無效。
4. 給 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的第一項(xiàng),或者添加enforce: 'pre'來保證首先應(yīng)用eslint-loader,因?yàn)槭且獙ξ覀兊脑创a進(jìn)行檢查,檢查要在babel-loader等其他編譯之前。
5. 安裝 vscode 的 eslint 插件
插件中搜 eslint 直接安裝,就可以在編輯器擁有實(shí)時(shí)錯(cuò)誤標(biāo)紅。
然后在 settings.json 中添加:
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
就可以在保存文件時(shí)自動 fix。
怎么打開
settings.json?左下角齒輪 -> 第一行 command ... -> 輸入open settings.json
6. 添加 .eslintignore 文件
編輯器中的檢測沒有指定路徑,所以會檢查 components 和 example 之外的文件,如果有些不想讓它檢查,可以根目錄添加 .eslintignore 文件。
build/
dist/
默認(rèn)包含
node_modules/
ESLint 就配置好了,包括 配置文件 + 執(zhí)行腳本 + webpack + 編輯器。
二、安裝配置 Prettier
1. 安裝 Prettier 包
npm i prettier -D
2. 新建 prettier.config.js 文件配置規(guī)則
prettier 的配置規(guī)則很少,推薦一套作為參考。
// prettier.config.js or .prettierrc.js
module.exports = {
// 一行最多 100 字符
printWidth: 100,
// 使用 4 個(gè)空格縮進(jìn)
tabWidth: 4,
// 不使用縮進(jìn)符,而使用空格
useTabs: false,
// 行尾需要有分號
semi: true,
// 使用單引號
singleQuote: true,
// 對象的 key 僅在必要時(shí)用引號
quoteProps: 'as-needed',
// jsx 不使用單引號,而使用雙引號
jsxSingleQuote: false,
// 末尾不需要逗號
trailingComma: 'none',
// 大括號內(nèi)的首尾需要空格
bracketSpacing: true,
// jsx 標(biāo)簽的反尖括號需要換行
jsxBracketSameLine: false,
// 箭頭函數(shù),只有一個(gè)參數(shù)的時(shí)候,也需要括號
arrowParens: 'always',
// 每個(gè)文件格式化的范圍是文件的全部內(nèi)容
rangeStart: 0,
rangeEnd: Infinity,
// 不需要寫文件開頭的 @prettier
requirePragma: false,
// 不需要自動在文件開頭插入 @prettier
insertPragma: false,
// 使用默認(rèn)的折行標(biāo)準(zhǔn)
proseWrap: 'preserve',
// 根據(jù)顯示樣式?jīng)Q定 html 要不要折行
htmlWhitespaceSensitivity: 'css',
// 換行符使用 lf
endOfLine: 'lf'
};
執(zhí)行檢查
npx prettier --test . // 全部文件
npx prettier --test components/ // 特定文件
執(zhí)行修復(fù)
npx prettier --write . // 全部文件
npx prettier --write components/ // 特定文件
3. 安裝 vscode 的插件,自動格式化
實(shí)際上不用執(zhí)行,直接安裝編輯器插件,保存文件就直接自動格式化了。
vscode 搜 prettier 直接安裝,然后在 settings.json 中添加配置:
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode"
遇到的問題
1.eslint 匹配不到文件會報(bào)錯(cuò)
剛開始 eslint 總是會報(bào)錯(cuò)
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.
然后發(fā)現(xiàn)是因?yàn)闆]有匹配到文件,就報(bào)錯(cuò)了。。
可以添加 flag --no-error-on-unmatched-pattern 禁止這種報(bào)錯(cuò)。
2.tsllint 已棄用
tslint 已經(jīng)于2019年1月就不再維護(hù),并提供到 typescript-eslint 的遷移,可以說 typescript-eslint 是目前支持 ts 的首選 lint。
3.prettier 不支持縮進(jìn)語法的 css 預(yù)編譯語言
prettier 支持非常多的文件類型,目前為止官網(wǎng)支持的文件如下:
- JavaScript (including experimental features)
- JSX
- Angular
- [Vue](https://links.jianshu.com/go?to=https%3A%2F%2Fvuejs.org%2F" target="_blank")
- Flow
- TypeScript
- CSS, Less, and SCSS
- HTML
- JSON
- GraphQL
- Markdown, including GFM and MDX
- YAML
要注意的是,對于樣式它和 stylelint 一樣,不支持縮進(jìn)格式風(fēng)格的.sass 和 .styl。
最后附上文檔地址
eslint rules: https://eslint.org/docs/rules/
eslint rules 中文: http://eslint.cn/docs/rules/
prettier 文檔: https://prettier.io/docs/en/index.html
typescript代碼檢查: https://ts.xcatliu.com/engineering/lint.html