vue知识点之找不到模块“@/xxx/xxx.vue”或其相应的类型声明。

Vite 和 TypeScript 处理模块和路径别名的方式略有不同,这就是为什么你可能需要在 tsconfig.json 中进行额外配置的原因。

一、Vite 中的路径别名

在 Vite 中配置路径别名主要用于客户端代码的模块解析。Vite 使用自己的解析策略,其中包括对 import.meta.url 的支持,这允许 Vite 在客户端构建时动态解析别名。当你在 vite.config.ts 中设置别名时:

// vite.config.ts
import { defineConfig } from 'vite';
import { fileURLToPath } from 'url';

export default defineConfig({
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  }
  // ...其他配置
});

这告诉 Vite 在构建过程中,将 @ 别名解析为 src 目录的路径。

二、TypeScript 中的路径别名

TypeScript 也支持路径别名,但是它是基于其自己的解析系统。TypeScript 在编译阶段工作,而不是在浏览器中解析模块。因此,为了让 TypeScript 理解你在 Vite 配置中的别名,你需要在 tsconfig.json 中添加相应的配置:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
    // ...其他配置
  }
}

posted on 2024-10-18 09:58  梁飞宇  阅读(185)  评论(0)    收藏  举报