【问题标题】:Uncaught ReferenceError: require not defined (electron)未捕获的 ReferenceError:需要未定义(电子)
【发布时间】:2020-07-19 04:29:35
【问题描述】:

我正在尝试在电子上创建一个报价小部件。对于渲染器进程,我创建了 index.js 并编码如下

console.log('from renderer');

var request = require('request');
const electron = require('electron');


var url ="https://quotesondesign.com/wp-json/wp/v2/posts/?orderby=rand&_="+rnd;

request(url, function(error, response, body) {
    if(error)
    {
        document.getElementById("quote").innerHTML = 'Unable to fetch the quote plaese check the network connection';
        return;
    }
    let bodyJSON = JSON.parse(body);
    console.log(bodyJson);
    let randomQuote = bodyJSON[0]["content"]["rendered"];
    document.getElementById("quote").innerHTML = randomQuote;
});

而index.html有

<div id="quote">

</div>
<script src="index.js">
    // require ('index.js');
</script>

如果我在script 标签中使用require ('index.js');,它就不起作用。所以我使用了src="index.js"。现在渲染器进程工作,但在控制台上,它显示"Uncaught ReferenceError: require is not defined at index.js:3" 我的第一个查询是为什么 require ('index.js'); 上的 script 标签在 index.html 上不起作用 第二个查询是如何解决index.js 上的Uncaught ReferenceError 问题 我的electron版本是v8.2.0,node版本是v12.16.1,对package.json的依赖如下:

"dependencies": {
        "request": "^2.88.2",
        "require": "^2.4.20"
    }

请任何人帮助我。提前致谢。

【问题讨论】:

    标签: javascript node.js electron


    【解决方案1】:

    从 Electron 5 开始,渲染器进程中的节点集成默认禁用。为了解决这个问题,您需要在实例化 BrowserWindow 时声明 nodeIntegration: true

    // In the main process.
    const { BrowserWindow } = require('electron')
    const mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
          nodeIntegration: true
        }
      })
    

    编辑:从 Electron 12 开始,您还需要定义 contextIsolation: false 才能执行此操作,因为标志的默认值已更改。

    https://www.electronjs.org/docs/breaking-changes#default-changed-contextisolation-defaults-to-true

    【讨论】:

    • 这对我有用,我也不需要更改“上下文”变量,但如果我尝试将电子应用程序作为网页并行使用“liveserver”,我无法让它工作,因为似乎这样做会使用户面临安全风险。所以作为网页的应用程序不能使用'require'
    【解决方案2】:

    require ('index.js'); 在 script 标签中不起作用的原因是因为 require 没有为浏览器定义。它仅针对 Node 定义。您在 index.js 中获得 ReferenceError 的原因是,&lt;script src="index.js&gt; 实际上是在浏览器环境中运行 index.js 中的代码。因此,由于它是在浏览器中运行的,require 也没有在这里定义。

    【讨论】:

    • 是的,我明白了,感谢您的回复。
    猜你喜欢
    • 2019-10-11
    • 2020-10-22
    • 2019-08-01
    • 2020-05-16
    • 2012-12-16
    • 2016-04-26
    • 1970-01-01
    • 2017-02-28
    相关资源
    最近更新 更多