[英]Uncaught ReferenceError: require not defined (electron)
我正在尝试在 electron 上创建报价小部件。 对于渲染器进程,我创建了 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;
});
并且索引.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');
on script
tag doesn't work on index.html
and 2nd query is how to fix the Uncaught ReferenceError
problem on index.js
My electron version is v8.2.0 and node version is v12.16.1 and dependencies on package.json
are as follows:
"dependencies": {
"request": "^2.88.2",
"require": "^2.4.20"
}
请任何人帮助我。 提前致谢。
从 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/break-changes#default-changed-contextisolation-defaults-to-true
require ('index.js');
在 script 标签中不起作用是因为没有为浏览器定义require
。 它仅针对 Node 定义。 你在 index.js 中得到ReferenceError
的原因是因为<script src="index.js>
实际上是在浏览器环境中运行 index.js 中的代码。所以因为它是在浏览器中运行的,所以require
这里也没有定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.