ESLint 在項目中的應用
在 vscode 中使用 ESLint 擴展,首選需要安裝 ESLint 擴展
為讓項目中代碼風格統一,需要解決配置中的沖突。
- 多個插件同時格式化一個文件。
- 一段代碼有 n 個 lint 規則沖突。
消除 vscode 集成插件沖突。
vscode 目前常用的格式化插件有 prettier,volar,eslint,vetur。
保存格式化與手動格式化配置需要一致,推薦 2 選一。
設置保存自動格式化文件,只使用 eslint
vscode settings
{
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
}
設置手動使用 eslint 格式化
手動格式化必須配置文件對應的格式化工具。如果沒有配置,格式化時 vscode 會列出所有可格式化此文件的插件供選擇。
手動格式化快捷鍵可以在代碼文件右鍵查看。
vscode settings
{
"eslint.format.enable": true,
"[javascript]": {
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
},
"[vue]": {
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
},
"[typescript]": {
"editor.defaultFormatter": "dbaeumer.vscode-eslint"
}
}
消除各種 lint 規則的沖突
添加插件
npm i @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint-config-prettier eslint-plugin-prettier prettier eslint-plugin-vue eslint -D
在目錄添加 .eslintrc.js
module.exports = {
root: true,
env: { node: true, 'vue/setup-compiler-macros': true },
// https://github.com/vuejs/vue-eslint-parser#parseroptionsparser
parser: 'vue-eslint-parser', // 所有文件的入口解析器
parserOptions: {
parser: '@typescript-eslint/parser', // ts解析器,vue解析器在遇到ts時使用ts解析器
ecmaVersion: 'latest', // 最新的語法也不會報錯
sourceType: 'module',
},
extends: [
// 使用插件中的configs 配置,里面含有rules,env等
'eslint:recommended', // eslint推薦的規則
'plugin:@typescript-eslint/recommended', // ts推薦的規則
'plugin:vue/vue3-recommended', // vue組件特有的規則
// "plugin:vue/recommended" // vue2使用
'plugin:prettier/recommended', // eslint-config-prettier 關閉與prettier沖突的規則,prettier接管代碼風格。其依賴需要eslint-plugin-prettier
],
rules: {
'no-undef': 0, // 關掉,typescript已經包含此規則
// 一下關閉的規則還需要討論。
'vue/script-setup-uses-vars': 2,
'vue/no-setup-props-destructure': 0,
'vue/multi-word-component-names': 0,
'vue/no-unused-vars': 0,
'vue/require-explicit-emits': 0,
'vue/valid-v-for': 0,
'vue/require-v-for-key': 1,
'@typescript-eslint/no-empty-function': 1,
'@typescript-eslint/ban-ts-comment': 0,
'@typescript-eslint/no-unused-vars': 1,
'@typescript-eslint/no-explicit-any': 0,
'@typescript-eslint/ban-types': 1,
'@typescript-eslint/no-namespace': 1,
},
}
配置prettier的代碼風格
也可以不使用prettier風格,全部使用eslint的風格(需要查看eslint文檔 樣式風格部分自己配置),但是eslint不支持某些文件的格式化,即使已手動配置了eslint格式化。
而prettier支持大多數語言的格式化。
配置prettierrc,供給eslint-plugin-prettier插件使用
.prettierrc
{
"prettier/prettier": [
// 配置prettier規則,也可以將所有規則放到.prettierrc 專用配置中
"warn",
{
"printWidth": 100,
"tabWidth": 2,
"useTabs": false,
"semi": false,
"jsxSingleQuote": true,
"singleQuote": true,
"arrowParens": "avoid",
"bracketSameLine": false,
"useEditorConfig": false,
"endOfLine": "auto"
}
]
}
使用命令格式化所有文件
package.json
{
"scripts": {
"lint": "eslint src --ext .vue,.ts --fix"
}
}
npm run lint
命令格式化 src 所有 ts 和 vue 文件