为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕斯王 2022-06-16 10:53:53
我正在尝试在电子上创建一个报价小部件。对于渲染器进程,我创建了 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"    }请任何人帮助我。提前致谢。
查看完整描述

2 回答

?
慕标5832272

TA贡献1966条经验 获得超4个赞

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


// 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


查看完整回答
反对 回复 2022-06-16
?
慕沐林林

TA贡献2016条经验 获得超9个赞

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



查看完整回答
反对 回复 2022-06-16

添加回答

代码语言

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号