猿问

未捕获的 ReferenceError:需要未定义(电子)

我正在尝试在电子上创建一个报价小部件。对于渲染器进程,我创建了 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>

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


"dependencies": {

        "request": "^2.88.2",

        "require": "^2.4.20"

    }

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


慕斯王
浏览 206回答 2
2回答

慕标5832272

从 Electron 5 开始,渲染器进程中的节点集成默认是禁用的。为了解决这个问题,您需要nodeIntegration: true在实例化您的BrowserWindow.// In the main process.const { BrowserWindow } = require('electron')const mainWindow = new BrowserWindow({&nbsp; &nbsp; width: 800,&nbsp; &nbsp; height: 600,&nbsp; &nbsp; webPreferences: {&nbsp; &nbsp; &nbsp; nodeIntegration: true&nbsp; &nbsp; }&nbsp; })编辑:从 Electron 12 开始,您还需要定义contextIsolation: false才能执行此操作,因为标志的默认值已更改。https://www.electronjs.org/docs/breaking-changes#default-changed-contextisolation-defaults-to-true

慕沐林林

require ('index.js');在 script 标签中不起作用的原因是require没有为浏览器定义。它仅针对 Node 定义。你得到ReferenceErrorin index.js 的原因是因为<script src="index.js>实际做的是在浏览器环境中运行 index.js 中的代码。因此,由于它在浏览器中运行,因此require这里也没有定义。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答