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

使用Vite集成React Testing Library时遇Vitest导出路径错误求助

解决React Testing Library + Vite集成时的"Package subpath "./utils" is not defined"错误

这个错误是Vite与Vitest版本不兼容导致的——你的Vite版本是3.2.7,而Vitest 0.34.1依赖的Vite版本要求是4.x及以上,版本不匹配触发了内部模块导出的路径问题。

以下是具体解决方法:

方法一:升级Vite到兼容版本

将Vite升级到和Vitest 0.34.1匹配的4.x系列版本(比如4.4.5),执行对应包管理命令:

# npm
npm install vite@^4.4.5 --save-dev

# yarn
yarn add vite@^4.4.5 --dev

# pnpm
pnpm add vite@^4.4.5 -D

方法二:降级Vitest到适配Vite 3.2.7的版本

如果不想升级Vite,可以把Vitest降级到支持Vite 3.x的版本(比如0.29.8):

# npm
npm install vitest@^0.29.8 --save-dev

# yarn
yarn add vitest@^0.29.8 --dev

# pnpm
pnpm add vitest@^0.29.8 -D

额外排查步骤

  1. 确认@testing-library相关包版本和React兼容:你的React 18.2.0和@testing-library/react 14.0.0是匹配的,这部分无需调整
  2. 若升级/降级后仍有问题,清理依赖重新安装:
# 清理依赖文件
rm -rf node_modules package-lock.json # npm用户
rm -rf node_modules yarn.lock # yarn用户
rm -rf node_modules pnpm-lock.yaml # pnpm用户

# 重新安装
npm install # 或 yarn / pnpm install
  1. 检查vite.config.js的测试配置是否正确,示例配置参考:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { configDefaults } from 'vitest/config'

export default defineConfig({
  plugins: [react()],
  test: {
    environment: 'jsdom',
    setupFiles: './src/test/setup.js', // 替换为你的setup文件路径
    exclude: [...configDefaults.exclude, 'e2e/*'],
    globals: true
  }
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 17:13:31