2023.08
安装eslint
参照 eslint官网步骤 https://eslint.org/docs/latest/use/getting-started
npm init @eslint/config
选择配置
- 选择模式 to check syntax, find problems, and enforce code style
- 选择语言模块 JavaScript
- 语言框架 vue
- 是否使用ts yes
- 代码在哪里运行 Browser
- 风格指南 standard
- 配置文件格式 JavaScript
- 是否现在安装,用什么包管理器来下载 yarn
此时页面会出现一个.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"
},
执行yarn lint命令
1.报错 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 添加配置
配置对应TypeScript对应的语法解析器
"parserOptions": {
.....
"parser": "@typescript-eslint/parser",
"project": './tsconfig.json',
....
},
esLint 默认的 parser ,只转换 js,默认支持 ES5 的语法,所以t项目需要通过制定 parserOptions 传递对应的解析选项。
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 报错
"env": {
"browser": true,
"es2021": true
},
"extends": [
"plugin:vue/vue3-essential", // vue3-base校验
"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来解析.vue文件
vue 官方提供了一个 ESLint 插件 eslint-plugin-vue,它提供了 parser 和 rules。parser 为 vue-eslint-parser,rules 为 https://eslint.vuejs.org/rules/。