简体   繁体   English

将电子渲染器添加到 webpack 时“需要未定义”

[英]'Require is not defined' when adding electron-renderer to webpack

I am developing an electron app.我正在开发一个电子应用程序。 All good and nice until I wanted to use IPC from the renderer to call some native features.一切都很好,直到我想使用来自渲染器的 IPC 来调用一些本机功能。 I understand that adding the following line to my Webpack config would allow me to import electron on the renderer side.我知道将以下行添加到我的 Webpack 配置中将允许我在渲染器端导入电子。

module.exports = {
    // ...
    target: 'electron-renderer',
}

I get the following error when adding this line添加此行时出现以下错误

Uncaught ReferenceError: require is not defined

And the offending line is违规行是

module.exports = require("querystring");

Which sort of makes sense, since the browser does not understand "requires".哪一种是有道理的,因为浏览器不理解“需要”。

Note that without the electron-renderer target the application works well, except I cannot do things like请注意,如果没有electron-renderer目标,应用程序运行良好,除了我不能做这样的事情

import {ipcRenderer} from 'electron';

Any thoughts what I could be doing wrong?任何想法我可能做错了什么? Thank you!谢谢!

Just recently ran into this.最近刚遇到这个。 One thing to look out for is to ensure nodeIntegration is set to true when creating your renderer windows.需要注意的一件事是确保在创建渲染器窗口时将 nodeIntegration 设置为 true。

mainWindow = new electron.BrowserWindow({
    width: width,
    height: height,
    webPreferences: {
        nodeIntegration: true
    }
});

Also faced this issue, new answer:也面临这个问题,新答案:

mainWindow = new electron.BrowserWindow({
    width: width,
    height: height,
    webPreferences: {
        nodeIntegration: true,
        contextIsolation: false
    }
});

AFAIU the recommended way is to use contextBridge module (in the preload.js script). AFAIU 推荐的方法是使用contextBridge模块(在preload.js脚本中)。 It allows you to keep the context isolation enabled but safely expose your APIs to the context the website is running in.它允许您保持启用上下文隔离,但安全地将您的 API 暴露给网站运行的上下文。

https://www.electronjs.org/docs/latest/tutorial/context-isolation https://www.electronjs.org/docs/latest/tutorial/context-isolation

Following this way, I also found that it was no longer necessary to specify target property in the Webpack config.通过这种方式,我也发现不再需要在 Webpack 配置中指定target属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM