Vite构建React应用后出现Require is not defined错误的解决方法
解决Vite构建React应用时
react-comments-section包的"required is not defined"错误 以下是针对该问题的具体配置调整方案:
方案1:优化Vite内置CommonJS转换配置
移除单独的vite-plugin-commonjs插件,改用Vite内置的CommonJS处理能力,避免插件冲突:
import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; export default defineConfig({ plugins: [react()], define: { global: "window", // 将global指向浏览器环境的window对象 }, build: { commonjsOptions: { transformMixedEsModules: true, // 明确指定需要转换CommonJS语法的包路径 include: [/node_modules\/@pmhieu\/react-comments-section/, /node_modules/] } }, optimizeDeps: { include: ["@pmhieu/react-comments-section"], force: true, // 强制预构建该包,确保转换逻辑生效 }, resolve: { alias: { src: "/src", }, }, });
方案2:添加ESBuild转换规则
如果方案1无效,可在optimizeDeps中配置ESBuild加载器,强制将该包的JS文件按JSX规则处理并转换CommonJS语法:
import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; export default defineConfig({ plugins: [react()], define: { global: "window", }, build: { commonjsOptions: { transformMixedEsModules: true } }, optimizeDeps: { include: ["@pmhieu/react-comments-section"], force: true, esbuildOptions: { loader: { ".js": "jsx", // 强制将该包的JS文件按JSX语法解析 }, }, }, resolve: { alias: { src: "/src", }, }, });
方案3:手动包装组件转换语法
如果上述方案都无效,可以在项目中对该包进行二次包装,将CommonJS语法转换为ES模块:
- 在
src/utils目录下创建CommentsWrapper.jsx文件:
// 通过CommonJS导入后,以ES模块格式导出 const CommentsSection = require("@pmhieu/react-comments-section").default; export default CommentsSection;
- 在项目业务代码中使用这个包装后的组件:
import CommentsSection from './utils/CommentsWrapper';
同时保持Vite配置中build.commonjsOptions.transformMixedEsModules: true的设置。
内容的提问来源于stack exchange,提问作者hieuph13
相关产品推荐
相关产品推荐

