2023.08
安裝eslint
參照 eslint官網(wǎng)步驟 https://eslint.org/docs/latest/use/getting-started
npm init @eslint/config
選擇配置
- 選擇模式 to check syntax, find problems, and enforce code style
- 選擇語(yǔ)言模塊 JavaScript
- 語(yǔ)言框架 vue
- 是否使用ts yes
- 代碼在哪里運(yùn)行 Browser
- 風(fēng)格指南 standard
- 配置文件格式 JavaScript
- 是否現(xiàn)在安裝,用什么包管理器來(lái)下載 yarn
此時(shí)頁(yè)面會(huì)出現(xiàn)一個(gè).eslintrc.cjs文件
配置package.json
增加lint命令
"scripts": {
"dev": "vite",
"build": "vue-tsc && vite build",
"preview": "vite preview",
"lint": "eslint './src/**/*.{js,jsx,vue,ts,tsx}' --fix"
},
執(zhí)行yarn lint命令
1.報(bào)錯(cuò) parserOptions.project
Error: Error while loading rule '@typescript-eslint/dot-notation': You have used a rule which requires parserServices to be generated. You must therefore provide a value for the "parserOptions.project" property for @typescript-eslint/parser.
解決方式:
在.eslintrc.cjs 添加配置
配置對(duì)應(yīng)TypeScript對(duì)應(yīng)的語(yǔ)法解析器
"parserOptions": {
.....
"parser": "@typescript-eslint/parser",
"project": './tsconfig.json',
....
},
esLint 默認(rèn)的 parser ,只轉(zhuǎn)換 js,默認(rèn)支持 ES5 的語(yǔ)法,所以t項(xiàng)目需要通過(guò)制定 parserOptions 傳遞對(duì)應(yīng)的解析選項(xiàng)。
2.file (.vue) is non-standard
error Parsing error: ESLint was configured to run on <tsconfigRootDir>/src/App.vue using parserOptions.project: xxxx/tsconfig.json
The extension for the file (.vue) is non-standard. You should add parserOptions.extraFileExtensions to your config
解決:
.eslintrc.cjs
"parserOptions": {
....
....
"extraFileExtensions": ['.vue'],
},
3.error Parsing error: '>' expected
.eslintrc.cjs
"parser": "vue-eslint-parser",
.eslintrc.cjs
module.exports = {
"parser": "vue-eslint-parser", // 解決 Parsing error: '>' expected 報(bào)錯(cuò)
"env": {
"browser": true,
"es2021": true
},
"extends": [
"plugin:vue/vue3-essential", // vue3-base校驗(yàn)
"standard-with-typescript"
],
"overrides": [
{
"env": {
"node": true
},
"files": [
".eslintrc.{js,cjs}"
],
"parserOptions": {
"sourceType": "script"
}
}
],
"parserOptions": {
"parser": "@typescript-eslint/parser",
"project": './tsconfig.json',
"ecmaVersion": "latest",
"sourceType": "module",
"extraFileExtensions": ['.vue'],
},
"plugins": [
"vue"
],
"rules": {
......
}
}
使用vue-eslint-parser來(lái)解析.vue文件
vue 官方提供了一個(gè) ESLint 插件 eslint-plugin-vue,它提供了 parser 和 rules。parser 為 vue-eslint-parser,rules 為 https://eslint.vuejs.org/rules/。