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

Vite使用绝对导入TypeScript枚举时构建失败求助

Vite构建TypeScript枚举绝对导入失败问题

问题描述

使用绝对导入TypeScript枚举时,TypeScript可正常解析路径,但Vite构建预览时抛出错误:

[plugin:vite:import-analysis] Failed to resolve import "@enums/common" from "src/path/to/file.tsx". Does the file exist?

仅枚举的导入/导出受影响,类型或其他数据的绝对导入可正常工作。已引入vite-tsconfig-paths插件对齐TypeScript解析逻辑,但问题未解决。

相关配置与代码

tsconfig.json

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

vite.config.ts

/// <reference types="vitest" />
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tsconfigPaths from 'vite-tsconfig-paths'

export default defineConfig({
  plugins: [react(), tsconfigPaths()],
  test: {
    globals: true,
    environment: 'jsdom',
    setupFiles: './test/setup.js',
  },
})

枚举文件

src/enums/common/fooEnum.ts

// 注:原代码存在语法错误,正确写法如下
export enum Foo {
  BAR = 'bar',
  BAZ = 'baz'
}

src/enums/common/index.ts

export { Foo } from './fooEnum'

组件导入代码

reactComponent.tsx

import { Foo } from '@types/common'

使用技术版本

  • React v18.2
  • Vite v4.1
  • vite-tsconfig-paths v4.2
  • TypeScript v4.9

解决方案

  1. 调整路径映射顺序
    tsconfig.json中@*的通配规则会优先匹配所有以@开头的路径,覆盖后面的@types/*规则,导致@types/common被解析为src/types/common而非预期的src/enums/common。需将更具体的规则放在前面:
"paths": {
  "@types/*": [
    "src/enums/*"
  ],
  "@*": [
    "src/*"
  ]
}
  1. 修复枚举语法错误
    原枚举定义存在语法错误(export enum foo = { ... }),正确写法应为export enum Foo { ... },语法错误会导致编译异常,间接影响Vite的路径解析。

  2. 清除缓存并重启服务
    执行vite --clearScreen false清除Vite缓存,或手动删除node_modules/.vite目录后重启开发服务器,确保配置修改生效。

  3. 统一路径命名(可选)
    若上述调整仍有问题,可新增@enums/*的独立映射,避免通配规则冲突:

"paths": {
  "@enums/*": [
    "src/enums/*"
  ],
  "@*": [
    "src/*"
  ]
}

组件中改为:

import { Foo } from '@enums/common'

内容的提问来源于stack exchange,提问作者Raul Calvo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 23:12:37