使用Yarn3.3.0+TS从CRA(Webpack)迁移到Vite时浏览器出现导出错误
解决Vite迁移后出现“Export 'import_react3' is not defined”错误的方案
可能的原因及对应解决方法
1. 检查Vite React插件配置
确保项目正确安装并配置了@vitejs/plugin-react——CRA的JSX自动导入逻辑在Vite中需要该插件支持:
- 确认依赖已安装:
yarn add @vitejs/plugin-react --dev - 在
vite.config.ts中正确配置插件:import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' export default defineConfig({ plugins: [react()], })
2. 临时禁用Yarn 3的PnP模式排查
Yarn 3的PnP特性可能和Vite存在兼容性冲突,可切换到node_modules模式测试:
yarn config set nodeLinker node-modules yarn install
重启yarn dev后查看错误是否消失。
3. 清理缓存并重建项目
Vite的缓存可能残留异常编译文件,执行以下命令清理:
yarn cache clean rm -rf node_modules .vite dist yarn install yarn dev
4. 对齐React/ReactDOM版本
确保新项目中React和ReactDOM的版本与旧项目完全一致,避免版本不匹配导致的编译异常:
- 查看旧项目版本:
yarn list react react-dom - 在新项目中安装对应版本:
yarn add react@x.x.x react-dom@x.x.x
(将x.x.x替换为旧项目的具体版本号)
5. 检查组件导入语法
排查所有组件中的React导入是否规范,避免重复导入、别名错误或未正确导出的模块:
- 标准导入方式:
import React from 'react' // 或在Vite+React插件配置下可省略React导入(插件自动注入)
内容的提问来源于stack exchange,提问作者Nahidujjaman Hridoy
相关产品推荐
相关产品推荐

