[英]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.