electron 5.0.0 "Uncaught ReferenceError: require is not defined"

electron 5.0.0 "Uncaught ReferenceError: require is not defined"

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

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

事实证明,nodeIntegration在以前的electron版本中默认为true,但在5.0.0中默认为false。因此,将其设置为 true 解决了我的问题。在评论或电子页面上找不到在线记录的此更改,我想我会做这个自我回答 SO post 以便将来遇到此问题的人更容易找到。

junvar所说,nodeIntegration在5.0.0中默认为false。

electronjs FAQ 有一些关于如何设置这个值的示例代码。

let win = new BrowserWindow({
  webPreferences: {
    nodeIntegration: true
  }
})
win.show()

junvar是对的,nodeIntegration在v5.0.0中默认是假的。

这是 Release Notes for v5.0.0 and was also mentioned in this PR

Other Changes 部分的最后一条语句

创建新浏览器时将 nodeIntegration 设置为 true window。

app.on('ready', () => {
    mainWindow = new BrowserWindow({
        webPreferences: {
            nodeIntegration: true
        }
    });
});

此 post 的读者在做出决定之前应阅读 Do not enable Node.js Integration for Remote Content section from the Security, Native Capabilities, and Your Responsibility Guide

// Bad
const mainWindow = new BrowserWindow({
  webPreferences: {
    nodeIntegration: true,
    nodeIntegrationInWorker: true
  }
})
mainWindow.loadURL('https://example.com')

// Good
const mainWindow = new BrowserWindow({
  webPreferences: {
    preload: path.join(app.getAppPath(), 'preload.js')
  }
})
mainWindow.loadURL('https://example.com')

Electron 版本 12 及以上

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`);
});

webPreferences

中添加contextIsolation: false

假设电子12.0.0

设置contextIsolation: false

保留以下代码 main.js

new BrowserWindow({
        width: 800, height: 600,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
            enableRemoteModule: true,
          }
    })

电子13.0.0

webPreferences: {
  nodeIntegration: true,
  contextIsolation: false,
  enableRemoteModule: true
}

你应该设置contextIsolation: false

如果您这样做,正如几个答案所建议的那样,那么您的代码肯定不会再因“Uncaught ReferenceError: require is not defined.”而失败。

但这只是因为您禁用了整个安全功能! Context Isolation 自 Electron 12 以来默认启用,因为它是所有 Electron 应用程序的重要安全功能。如果你设置contextIsolation: false,这就像把你家前门的锁拿掉,让你的家人进出成为可能,而不是给那些允许进入的人提供钥匙。

而不是,您应该设置contextIsolation: true(默认值)和使用预加载脚本为您的应用程序可能需要的任何模块公开白名单包装器。您可以在 Context Isolation link 阅读更多相关信息,并且在 .

中有一个详细的示例