Realm是否兼容Electron-React?按官方文档集成时报require未定义错误
问题修复方案
1. 修复electron.js配置错误
当前electron.js存在两处错误:
- 缺失electron模块导入声明
- 高版本Electron默认开启上下文隔离,仅开启nodeIntegration不足以让渲染进程调用require
修改后的完整代码如下:
const path = require('path'); // 新增electron模块导入 const electron = require('electron'); const app = electron.app; const BrowserWindow = electron.BrowserWindow; let mainWindow; function createWindow() { mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true, // 新增关闭上下文隔离配置 contextIsolation: false }, }); console.log(__dirname); mainWindow.loadFile(path.join(__dirname, '../build/index.html')); } app.on('ready', createWindow);
2. 修复craco.config.js配置错误
当前craco.config.js缺失nodeExternals模块导入,需要先安装对应依赖再补全配置:
- 安装依赖命令:
npm install webpack-node-externals --save-dev - 修改后的完整代码如下:
// 新增nodeExternals模块导入 const nodeExternals = require('webpack-node-externals'); module.exports = { webpack: { configure: { target: 'electron-renderer', externals: [ nodeExternals({ allowlist: [/webpack(\/.*)?/, 'electron-devtools-installer'], }), ], }, }, };
3. 重新执行构建启动流程
所有配置修改完成后,依次执行以下命令即可恢复正常运行:
- 执行项目构建:
npm run build - 启动Electron应用:
npm start
内容的提问来源于stack exchange,提问作者caser
相关产品推荐
相关产品推荐

