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

Electron应用中require未定义问题求助

Electron中解决require is not defined报错的方案

核心问题

你遇到的问题是**contextIsolation和nodeIntegration同时开启导致的冲突**:当Electron的contextIsolation设为true时,nodeIntegration的设置会被忽略,渲染进程(renderer.js)无法直接访问Node.js的require API。


方案一:使用Preload脚本桥接(推荐,符合安全规范)

Electron官方推荐保持contextIsolation开启,通过preload脚本安全地暴露Node.js模块到渲染进程:

  1. 编写preload.js:
const { contextBridge } = require('electron');
const websocketio = require('websocketio');

// 向渲染进程暴露API
contextBridge.exposeInMainWorld('electronAPI', {
  socket: websocketio
});
  1. 修正main.js的webPreferences配置:
webPreferences: {
  contextIsolation: true, // 保持开启,遵循安全最佳实践
  preload: path.join(__dirname, 'preload.js'),
  // nodeIntegration可以移除或设为false,因为contextIsolation开启时它不生效
}
  1. 在renderer.js中调用暴露的API:
window.socket = window.electronAPI.socket;

方案二:关闭contextIsolation(仅用于开发测试,不推荐生产环境)

如果只是开发阶段临时测试,可以关闭contextIsolation来让nodeIntegration生效:

// 修改main.js的webPreferences
webPreferences: {
  contextIsolation: false,
  nodeIntegration: true,
}

修改后,renderer.js中的window.socket = require('websocketio')就能正常运行,但这种方式会让渲染进程直接拥有所有Node.js权限,生产环境下存在严重安全风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 10:32:14