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

mdm*_*afa 1 javascript node.js 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;
});
Run Code Online (Sandbox Code Playgroud)

而 index.html 有

<div id="quote">

</div>
<script src="index.js">
    // require ('index.js');
</script>
Run Code Online (Sandbox Code Playgroud)

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

"dependencies": {
        "request": "^2.88.2",
        "require": "^2.4.20"
    }
Run Code Online (Sandbox Code Playgroud)

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

eri*_*ick 8

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

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

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

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