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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/56091343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 10:35:43  来源:igfitidea点击:

TypeError: window.require is not a function

javascriptnode.jselectron

提问by Manfreds3

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 requireworks onlyin main.js.

我正在尝试构建一个电子应用程序并想使用 window.require。不幸的是,编译器说“TypeError:window.require 不是函数”。具有讽刺意味的是,require在 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')

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

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

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

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

作者还说使用“nodeRequire”而不是 require 可以解决问题,但它不会......

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.

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

回答by spring

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

目前尚不清楚Electron您使用的是哪个版本。您使用的语法是非标准的。

First – if you are using Electron5.0, nodeIntegration is false by defaultin BrowserWindowsso you need to specify it explicitly when you create your window:

首先 - 如果您使用的是Electron5.0,则nodeIntegration 默认为 falseBrowserWindows因此您需要在创建窗口时明确指定它:

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');