[英]TypeError: window.require is not a function
我正在尝试构建一个 electron 应用程序并想使用 window.require。 不幸的是,编译器说“TypeError:window.require 不是函数”。 具有讽刺意味的是,要求仅在 main.js 中有效。
这是我试图运行的代码:
const electron = window.require('electron')
const low = window.require('lowdb')
const FileSync = window.require('lowdb/adapters/FileSync')
我在另一篇文章中读到有人遇到了同样的问题,并通过将此代码添加到 .html 文件中来解决此问题:
<script type="text/javascript" src="../../../Gehaltseinstellungen_Hinzufügen.js">
window.nodeRequire = require;
delete window.require;
delete window.exports;
delete window.module;
</script>
作者还说使用“nodeRequire”而不是require可以解决问题,但它并没有......
我读到的另一个选项是在激活渲染过程时将 NodeIntegration 设置为 false,但我不知道如何在渲染时激活 Node。
目前尚不清楚您使用的是哪个版本的Electron
。 您使用的语法是非标准的。
首先——如果您使用的是Electron
5.0,则BrowserWindows中的BrowserWindows
默认为 false,因此您需要在创建窗口时明确指定它:
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
鉴于上述情况,下面的语法工作正常(即不需要“窗口”引用):
const { ipcRenderer, remote } = require('electron');
您可以像这样将webPreferences.contextIsolation设置为false
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
它可能有效
需要像这样的所有 3 个设置才能完成这项工作:
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
contextIsolation: false,
},
注意:macbook m1,big sur 11.4,也许它必须对操作系统,idk 做一些事情。
Electron + React + Typescript 中的相同问题。 这为我解决了
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
contextIsolation: false
}
我也在 Electron + Angular 中遇到过这个问题。
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
上面的配置对我有用。
我被这个问题困扰了几天。 无法弄清楚我的生活。 浏览了很多文档和stackoverflow,最后!!!!
我通过以下方式修复了此错误:
创建一个文件 preload.js :
const { remote } = require('electron');
window.ipcRenderer = require('electron').ipcRenderer;
然后在 main.js/electron.js 中:
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
//this line is crucial
preload: path.join(app.getAppPath(), '/path-to-file/preload.js'),
contextIsolation: false
}
})
最后在 App.js 中:
const { ipcRenderer } = window
我从电子窗口中获得了 ipcRenderer。 我很确定你可以得到任何你想要的东西。
您不需要按照建议修改 web 首选项,我建议您不要这样做,除非您有更好的理由,因为隐含的安全问题( https://www.electronjs.org/docs/latest/tutorial /security#isolation-for-untrusted-content )。
相反,您可以做的是使用预加载脚本将您需要的任何功能添加到window
。 像这样的例子:
preload.js(位于根文件夹中):
contextBridge.exposeInMainWorld('ipcRenderer', {
invoke: (event) => ipcRenderer.invoke(event),
});
main.js 中的 webPreferences:
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
}
现在在您的代码中,您可以引用它:
const { ipcRenderer } = window as any;
const response = await ipcRenderer.invoke(...);
此处参考文档: https://www.electronjs.org/docs/latest/tutorial/tutorial-preload#communicating-between-processes
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.