本文用到的技术栈有:
- Vue3.0
- vite
- eslint
前言
随着项目越来越大,每个开发人员的代码风格很难统一,这时候我们就用到了eslint
。当然,eslint的用法很多,感兴趣的朋友可以去官网自己查阅,本文只详细解决一个问题:vue中如何让eslint识别配置的路径别名。
创建项目
yarn create vite
备注:记得选择vue
+ts
配置vite的别名
// vite.config.ts
import { defineConfig } from 'vite'
import path from 'path'
export default defineConfig({
resolve: {
alias: {
"/@": path.resolve(__dirname, "./src/components")
}
}
})
先看问题
上面基础工作做完之后,我们来看一下我们今天要解决什么问题?
下面这个问题是我新创建的vite+vue3.0+eslint
的模板,并且使用了别名来引入组件所产生的一个错误。(不会配置eslint的同学参考我另外一篇文章)
主要看红框圈出的那个错误:不能引入这个模块。虽然我们vite
中已经配置了路径别名,但是eslint
并不能读取我们vite
中的配置。怎么做?继续看。
安装依赖
需要eslint-import-resolver-alias
这个插件,附上官方文档链接:
yarn add eslint-import-resolver-alias -D
配置eslint
// .eslintrc.js文件中
module.exports = {
...
settings: {
"import/resolver": {
alias: [["/@", "./src"]],
},
},
...
}
使用时
比如我们要引用src/components/HelloWorld.vue
组件
import HelloWorld from "/@/components/HelloWorld.vue";
结果测试
成功解决了eslint中,路径别名报错的问题。图片中的另外一个绝对路径的报错,请参考这里。
ts识别路径别名
如果你的项目中还使用了Typescript
,那么你还需要配置tsconfig.json
。因为ts现在不识别你的路径别名无法给你相应的检查以及提示。
配置tsconfig.json
其余的配置我就直接省略了,现在直接看跟这个问题相关的配置。如果想看tsconfig.json
全部配置属性,请点击这里。
{
"compilerOptions": {
...,
"baseUrl": ".",
"paths": {
"/@/*": [
"src/*"
]
},
},
}
看一下效果,是不是舒服多了。