1. 项目说明
- 主技术栈: Vite + Vue3 + TypeScript
- 项目中版本情况:
"Vite":"3.0.0""Vue":"3.2.37""Ts":"4.6.4"
- 出现问题: 在配置完Vite后,正常开发没问题,但是Ts类型检查报错:找不到模块"/xxx/xxx/xxx"或其相应的类型声明
2. 解决方法
- 首先要配置Vite,根据官方文档中的给出的类型说明:
Record<string,string>|Array<{ find:string| RegExp, replacement:string}>
由此可知:我们可以配置alias为一个对象,或一个 { find, replacement } 的数组
- 具体配置: 在根目录中的 vite.config.ts 中加入如下配置:(以下是我个人项目配置)
import{ resolve }from"path";// 导入 path 模块,帮助我们解析路径exportdefaultdefineConfig({
resolve:{// 这里配置需要注意:Vite新版本resolve配置改为对象形式,如下:
alias:[{
find:'@',
replacement:resolve(__dirname,"src"),},{
find:'comps',
replacement:resolve(__dirname,"src/components"),},{
find:'apis',
replacement:resolve(__dirname,"src/apis"),},{
find:'views',
replacement:resolve(__dirname,"src/views"),},{
find:'routes',
replacement:resolve(__dirname,"src/router"),},{
find:'store',
replacement:resolve(__dirname,"src/store"),},{
find:'utils',
replacement:resolve(__dirname,"src/utils"),},{
find:'styles',
replacement:resolve(__dirname,"src/styles"),},{
find:'layout',
replacement:resolve(__dirname,"src/Layout"),},{
find:'models',
replacement:resolve(__dirname,"src/models"),},{
find:'hooks',
replacement:resolve(__dirname,'src/hooks')}],}})
- 这样配置完成后,项目中可以正常使用,但是Ts类型检查会提示错误,接着,配置根目录下的 ts.config.json 文件:(这里还是我个人的配置,分别对应Vite中配置好的别名)
注意:主要配置 baseUrl 和 paths 两个配置项即可,其他选项是初始化项目自动生成的
{"compilerOptions":{"target":"ESNext","useDefineForClassFields":true,"module":"ESNext","moduleResolution":"Node","strict":true,"jsx":"preserve","sourceMap":true,"resolveJsonModule":true,"isolatedModules":true,"esModuleInterop":true,"lib":["ESNext","DOM"],"skipLibCheck":true,"baseUrl":"./","paths":{"@/*":["src/*"],"comps/*":["src/components/*"],"apis/*":["src/apis/*"],"views/*":["src/views/*"],"routes/*":["src/router/*"],"store/*":["src/store/*"],"utils/*":["src/utils/*"],"styles/*":["src/styles/*"],"layout/*":["src/Layout/*"],"models/*":["src/models/*"],"hooks/*":["src/hooks/*"]}},"include":["src/**/*.ts","src/**/*.d.ts","src/**/*.tsx","src/**/*.vue"],"references":[{"path":"./tsconfig.node.json"}]}
- 配置完成后,Ts类型检查就不会报错了。(反应慢的重启一下VsCode)
本文转载自: https://blog.csdn.net/qq_45064834/article/details/126860182
版权归原作者 ぃ Gavin 所有, 如有侵权,请联系我们删除。
版权归原作者 ぃ Gavin 所有, 如有侵权,请联系我们删除。