电子 5.0.0 “未捕获的参考错误:未定义要求"

2022-01-10 00:00:00 node.js electron javascript require

我最初使用的是 electron stable (4.x.x),并且能够在我的浏览器和渲染器进程中使用 require.我升级到 electron beta (5.0.0) 因为我需要更新版本的节点并且在我的渲染器进程中遇到了这个错误消息,Uncaught ReferenceError: require is not defined.

I had initially been using electron stable (4.x.x), and was able to use require in both my browser and renderer processes. I upgraded to electron beta (5.0.0) because I needed a newer version of node and encountered this error message in my renderer process, Uncaught ReferenceError: require is not defined.

谷歌搜索并查看电子文档,我发现评论说错误可能是由于在初始化 BrowserWindow 时将 webPreferences.nodeIntegration 设置为 false 引起的;例如:new BrowserWindow({width, height, webPreferences: {nodeIntegration: false}});.但我并没有这样做,所以我认为一定是其他问题,并继续寻找解决方案.

Googling and looking through the electron docs, I found comments saying the error could be caused by setting webPreferences.nodeIntegration to false when initializing the BrowserWindow; e.g.: new BrowserWindow({width, height, webPreferences: {nodeIntegration: false}});. But I was not doing this, so I thought something else must be the issue and continued searching for a resolution.

推荐答案

适用于 Electron 12 及以上版本

For Electron version 12 and above

const electron = require("electron");

const { app, BrowserWindow } = electron;

app.on("ready", () => {
  const mainWindow = new BrowserWindow({
    width: 1000,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: true,
    },
  });
  mainWindow.loadURL(`file://${__dirname}/index.html`);
});

相关文章