为 Vite 项目创建 import 解析的别名
· 约 1 分钟阅读
在使用 Vite 构建前端应用时,为了简化代码,可以设置 import 解析的别名,比如将代码根路径的别名设置为 @。
设置 vite
在 vite.config.ts 添加路径别名:
import { defineConfig } from "vite";import { fileURLToPath, URL } from "node:url";import vue from "@vitejs/plugin-vue";
// https://vitejs.dev/config/export default defineConfig({ plugins: [vue()], resolve: { alias: { "@": fileURLToPath(new URL("./src", import.meta.url)), }, },});让编辑器或者 IDE 识别别名
在 tsconfig.json 添加配置:
{ "compilerOptions": { // ... "paths": { "@/*": ["./src/*", "./dist/*"] } // ... } // ...}让编辑器/IDE 识别 VueJS 组件
此时,在 Typescript 代码中导入 .*vue 模块时,VS Code、Zed 等编辑器可能会报如下错误:
Cannot find module '@/App.vue' or its corresponding type declarations.ts(2307)解决方法是,新建 src/shims-vue.d.ts 文件,并添加如下内容:
declare module "*.vue";使用别名
在代码中使用 @/... 即可引用其他模块,比如:
import { httpClient } from "@/http/client";此时在编辑器或者 IDE 中能够跳转模块,即可说明配置成功。