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

Electron-React集成报错:window.require is not a function 求助

解决React + Electron中"window.require is not a function"错误

错误原因

Electron 12及以上版本默认在渲染进程中禁用了Node.js集成,同时开启了上下文隔离(contextIsolation),这导致渲染进程无法直接访问window.require这类Node.js原生API,从而抛出该错误。

解决方案

方案1:使用Preload脚本(官方推荐,安全)

这是Electron官方指定的安全交互方式,通过预加载脚本将需要的Electron API安全暴露给渲染进程。

  1. 创建预加载脚本preload.js:
const { contextBridge, ipcRenderer } = require('electron');

// 仅暴露需要的ipcRenderer方法,避免全局暴露带来的安全风险
contextBridge.exposeInMainWorld('electronAPI', {
  send: (channel, data) => ipcRenderer.send(channel, data),
  on: (channel, listener) => ipcRenderer.on(channel, listener)
});
  1. 在主进程(如main.js)中配置BrowserWindow,指定preload脚本:
const { app, BrowserWindow } = require('electron');
const path = require('path');

function createWindow() {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      contextIsolation: true, // 保持开启,保障安全
      preload: path.join(__dirname, 'preload.js') // 指向你的preload脚本路径
    }
  });

  mainWindow.loadURL('http://localhost:3000'); // React开发服务地址
}

app.whenReady().then(createWindow);
  1. 在React的App.js中使用暴露的API:
import React from 'react';
import './App.css';

function App() {
  // 从全局对象获取暴露的electronAPI
  const { electronAPI } = window;

  // 示例:给主进程发送消息
  const sendTestMessage = () => {
    electronAPI.send('test-channel', 'Hello from React');
  };

  return (
    <div className="App">
      Rendered
      <button onClick={sendTestMessage}>Send Test Message</button>
    </div>
  );
}

export default App;

方案2:开启Node.js集成(不推荐,仅用于测试)

如果是临时开发测试场景,可通过开启Node.js集成、关闭上下文隔离来直接使用window.require,但此做法会让渲染进程获得完整Node.js权限,存在严重安全隐患,禁止用于生产环境。

修改主进程的BrowserWindow配置:

const mainWindow = new BrowserWindow({
  width: 800,
  height: 600,
  webPreferences: {
    nodeIntegration: true,
    contextIsolation: false
  }
});

此时App.js中的原代码即可正常运行:

import React from 'react';
import './App.css';

const { ipcRenderer } = window.require('electron');

function App() {
  return (
    <div className="App">Rendered</div>
  );
}

export default App;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 02:06:15