类型错误:window.require 不是函数

2022-01-10 00:00:00 node.js electron javascript

我正在尝试构建一个电子应用程序并想使用 window.require.不幸的是,编译器说TypeError:window.require 不是函数".具有讽刺意味的是,require仅在 main.js 中有效.

Im trying to build an electron app and want to use window.require. Unfortunately the compiler says "TypeError: window.require is not a function". Ironically require works only in main.js.

这是我试图运行的代码:

Here the code Im trying to run:

const electron = window.require('electron')
const low =  window.require('lowdb')
const FileSync = window.require('lowdb/adapters/FileSync')

我在另一篇文章中读到有人遇到了同样的问题,并通过将此代码添加到 .html 文件中解决了这个问题:

I read in another post that somebody have had the same problem and it was fixed by adding this code into the .html file:

    <script type="text/javascript" src="../../../Gehaltseinstellungen_Hinzufügen.js">
        window.nodeRequire = require;
        delete window.require;
        delete window.exports;
        delete window.module;
    </script>

作者还说使用nodeRequire"而不是 require 可以解决问题,但它并没有......

Also the author said using "nodeRequire" instead of require would solve the problem but it doesn't...

我读到的另一个选项是在激活渲染过程时 NodeIntegration 设置为 false,但我不知道如何在渲染时激活 Node.

Another option I read about is that the NodeIntegration is set to false while the rendering process is activated, but I don't know how to activate Node while rendering.

推荐答案

不清楚您使用的是什么版本的 Electron.您使用的语法是非标准的.

It is unclear what version of Electron you are using. The syntax you are using is non-standard.

首先 - 如果您使用的是 Electron 5.0,BrowserWindows 中的 nodeIntegration 默认为 false,因此您需要在创建窗口时明确指定它:

First – if you are using Electron 5.0, nodeIntegration is false by default in BrowserWindows so you need to specify it explicitly when you create your window:

mainWindow = new BrowserWindow({
  width: 800,
  height: 600,
  webPreferences: {
    nodeIntegration: true
  }
})

<小时>

鉴于上述情况,以下语法可以正常工作(即不需要窗口"引用):


Given the above, the syntax below works fine (i.e. no 'window' reference needed):

const { ipcRenderer, remote } = require('electron');

相关文章