Vite构建产物出现require未定义错误,多页面Electron应用求助
解决Vite+Electron多页应用中"require is not defined"错误
问题分析
单页切换多页后,Vite自动在project.js中插入了require('/index.xxx.js')语句,但Electron渲染进程的ES模块环境中未暴露CommonJS的require方法,导致报错。这通常是Rollup在多页共享chunk处理时,错误生成了CommonJS格式的引用,或是Electron渲染进程的Node API支持未覆盖所有页面入口。
解决方案
1. 强制Rollup输出ES模块
修改vite.config.js的build.rollupOptions.output,明确指定输出格式为ES模块,避免Rollup生成CommonJS风格的require:
export default defineConfig({ // ...其他配置 build: { assetsDir: '', rollupOptions: { input: { main: resolve(__dirname, 'index.html'), project: resolve(__dirname, 'project.html') }, output: { format: 'es', // 强制输出ES模块 entryFileNames: '[name].[hash].js', chunkFileNames: '[name].[hash].js' } }, }, })
2. 确保Electron渲染进程配置正确
检查Electron主进程中加载页面的窗口配置,确保开启Node集成并关闭上下文隔离(这是nodeIntegration生效的前提):
// electron/main.js const { BrowserWindow } = require('electron'); function createWindow(pagePath) { const win = new BrowserWindow({ webPreferences: { nodeIntegration: true, contextIsolation: false, // 必须关闭,否则Node API无法在渲染进程中使用 enableRemoteModule: true // 如果需要远程模块的话 } }); win.loadFile(pagePath); } // 加载主页面和项目页面 createWindow('dist/index.html'); createWindow('dist/project.html');
3. 调整Vite预加载策略
Vite自动生成的modulepreload可能触发了错误的chunk引用方式,可以尝试禁用自动预加载,改为手动控制:
export default defineConfig({ // ...其他配置 optimizeDeps: { modulepreload: false // 禁用自动模块预加载 } })
之后可以在project.html中手动添加需要的预加载资源,避免Vite自动生成错误的引用。
4. 检查vite-plugin-electron-renderer配置
确保插件正确处理所有多页入口,可尝试添加include字段指定所有渲染进程文件:
renderer({ nodeIntegration: true, include: ['src/**/*.js', 'src/**/*.vue'] // 覆盖所有渲染进程代码文件 })
验证
修改配置后重新构建运行,检查project.js中是否还存在require语句,同时确认Electron窗口加载project.html时不再报错。
内容的提问来源于stack exchange,提问作者d33p
相关产品推荐
相关产品推荐

