You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 23:27:03