如何在Vite.js项目中配置compilerOptions.baseUrl实现导入别名
Vite 兼容 CRA baseUrl 导入规则配置方案
1. 配置 vite.config.js 路径别名
CommonJS 格式配置(package.json 未设置 "type": "module")
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import path from 'path' export default defineConfig({ plugins: [react()], resolve: { alias: { // 匹配所有根路径导入,映射到 src 目录 '': path.resolve(__dirname, 'src') } } })
ESM 格式配置(package.json 已设置 "type": "module")
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import { fileURLToPath, URL } from 'node:url' export default defineConfig({ plugins: [react()], resolve: { alias: { '': fileURLToPath(new URL('./src', import.meta.url)) } } })
2. 保留原有 jsconfig.json 配置
你原本在 CRA 项目中使用的 jsconfig.json 无需修改,直接放在项目根目录即可,Vite 官方 React 插件会自动识别该配置提供代码提示,esbuild 底层会自动完成路径转换,无需额外配置esbuild规则。
{ "compilerOptions": { "baseUrl": "src" }, "include": ["src"] }
3. 验证效果
配置完成后重启 Vite 开发服务,原有 import Comp from 'components/MyComponent' 格式的导入语句会自动映射到 src/components/MyComponent,和 CRA 中的表现完全一致。
内容的提问来源于stack exchange,提问作者Fez Vrasta
相关产品推荐
相关产品推荐

