快速配置
- 使用vite的脚手架创建一个项目
yarn create vite
- 安装Eslint包
cd vite-project
yarn add
yarn add eslint -D
- 配置eslint
npx eslint --init
4. 安装依赖包
如果上一步中
Would you like to install them now with npm? 选择的为yes则可跳过当前步骤,否则,可以根据上一步骤的提示对需要的包进行安装
yarn add -D eslint-plugin-vue@latest @typescript-eslint/eslint-plugin@latest eslint-config-airbnb-base@latest eslint@^8.2.0 eslint-plugin-import@^2.25.2 @typescript-eslint/parser@latest
执行完以上的步骤基本的eslint配置就完成了,如果使用
vscode的同学一定要注意要重启vscode才能生效
深度定制配置
问题解决
问题1:
当我打开App.vue文件的时候发现下面的错误,这个规则一看就是vue2 的规则阿
解决方法
vue是使用
eslint-plugin-vue 这个插件对vue的格式进行校验的我们打开它的文档看一下
可以看出来 vue3 推荐的是 plugin:vue/vue3-recommended 这个规则,而我们的 eslintrc.js 中使用的是 plugin:vue/essential 这个,我们修改代码如下,重新打开 App.vue 问题修复。
module.exports = {
extends: [
- 'plugin:vue/essential',
+ 'plugin:vue/vue3-recommended',
'airbnb-base',
]
}
问题2:
当我安装上 vue-router 在app上使用时,报文件无法解析
解决方法
我们看到第一个错是 import/no-unresolved查看文档 主要原因是因为我们的文件名没有文件后缀所以文件不能被 require.resolve 方法所解析,通过添加一下代码,扩展解析器的解析后缀
module.exports = {
+ settings: {
+ 'import/resolver': {
+ node: {
+ extensions: [
+ '.js',
+ '.jsx',
+ '.ts',
+ ],
+ },
+ },
+ },
}
另一个错是报的是 import/extension 缺少文件后缀,通过查看文档我们添加如下代码解决
module.exports = {
+ 'import/extensions': ['error', 'always', {
+ js: 'never',
+ mjs: 'never',
+ jsx: 'never',
+ ts: 'never',
+ tsx: 'never',
+ }],
}
第一个参数为错误等级
error表示异常,第二个参数always代表必须使用扩展,第三个参数对特定类型的文件进行设置
配置 Alias
Eslint alias需要借助 eslint-import-resolver-alias 这个插件才能实现
yarn add eslint-import-resolver-alias -D
修改.eslintrc.js代码
module.exports = {
settings: {
+ 'import/resolver': {
+ alias: {
+ map: [
+ ['@components', './src/components'],
+ ],
+ extensions: ['.ts', '.js', '.jsx', '.json'],
+ },
+ },
},
}
为了让 vite 在构建的时候能够识别Alias我们需要在vite.config.ts中添加如下配置
export default defineConfig({
+ resolve: {
+ alias: { '@components': './src/components' },
+ },
})
配置Ts的 Eslint
ts 的语法lint 是使用
@typescript-eslint/eslint-plugin插件实现的,插件本身只能识别ts的内容,不能识别vue文件中的其他内容,所以我们需要先更换eslint 的parse 为 vue-eslint-parser之后在配置 ts 推荐的lint规则,参考如下代码完成配置。
yarn add vue-eslint-parser
修改 .eslintrc.js
module.exports = {
+ parser: 'vue-eslint-parser',
extends: [
+ 'plugin:@typescript-eslint/recommended',
+ 'plugin:@typescript-eslint/recommended-requiring-type-checking',
],
parserOptions: {
+ project: ['./tsconfig.eslint.json'],
+ extraFileExtensions: ['.vue'],
}
}
添加 tsconfig.eslint.json
{
"extends": "./tsconfig.json",
"include": ["./vite.config.ts",".eslintrc.js", "src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
}
在git commit 的时候进行类型校验
第一步
在 package.json 中添加 lint:script 命令
{
"scripts": {
+ "lint:script":"eslint --ext .js,.jsx,.ts,.tsx,.vue --fix ./",
},
}
执行 npm run lint:script 将对项目的代码进行检查
第二步
使用 lint-staged工具对暂存去的代码进行 lint
syarn add lint-staged -D
在 package.json 中添加如下代码
{
+ "lint-staged" : {
+ "**/*.{js,jsx,tsx,ts,vue}": [
+ "npm run lint:script" ,
+ "git add ."
+ ]
+ }
}
第三步
为了方便git 钩子的使用,我们需要安装 husky参考文档
yarn add husky -D
npx husky install
npm set-script prepare "husky install"
npx husky add .husky/pre-commit "npx --no lint-staged"