在电子渲染器进程中使用 npm 模块

using npm module in renderer process of electron

我已经通过 npm install Buffer 在我的机器上安装了 Buffer 模块,我想简单地将它导入渲染器进程以使用 Buffer

当我使用这个时:

const Buffer = require('Buffer')

它说要求未定义。

Stack Overflow 上的

None 个解决方案有效。

确保将 BrowserWindow 设置中的 nodeIntegration 设置为 true 并将 contextIsolation 设置为 false,如下所示:

new BrowserWindow({
    webPreferences:  {
        nodeIntegration:  true,
        contextIsolation: false
    },
});

默认情况下 nodeIntegrationfalse,这会阻止您在渲染器进程中使用 NPM 模块,打开 nodeIntegration 将解决此问题。

Read more here

NOTE: To access the Node.js API from the Renderer process, you need to set the nodeIntegration preference to true and the contextIsolation preference to false.

免责声明,打开 nodeIntegration 会在您的应用中打开安全漏洞。 关于如何修复它们。