2

我正在编写我的第一个电子应用程序,我试图在单击按钮时显示一个窗口。我有一条错误消息:

未捕获的 ReferenceError:在 dialog.js:2 中未定义要求

我正在使用“电子夜间”版本:“^6.0.0-nightly.20190213”

这是代码:

index.js:

const electron = require('electron');
const {app, BrowserWindow} = electron;
const path = require('path');
const url = require('url');

let win

function main(){

    win = new BrowserWindow({ width: 500, height: 400});

    win.loadURL(url.format( {
        pathname: path.join(__dirname, './index.html'),
        protocol: 'file',
        slashes: true
    } ));

    win.webContents.openDevTools()

}

exports.openDialog = () => {
    let dial = new BrowserWindow({ width: 400, height: 200});

    dial.loadURL(url.format( {
        pathname: path.join(__dirname, './dialog.html'),
        protocol: 'file',
        slashes: true
    } ));
}


app.on('ready', main);

索引.html:

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Hello world</title>
</head>
<body>

    <h1>Hello Electron!!</h1>

    <button id="btn">Show dialog</button>

    <script src="./dialog.js"></script>

</body>
</html>

对话框.js:

const index = require('electron').remote.require('./index.js'); //Error line: Uncaught ReferenceError: require is not defined at dialog.js:2

const button = document.getElementById('btn');

button.addEventListener('click', () => {
    index.openDialog();
});

这个错误是关于 ES6+ 的吗?

4

1 回答 1

2

您可能必须在新窗口中启用节点集成(根据文档默认禁用):

index.js

function main() {

  win = new BrowserWindow({
    width: 500,
    height: 400,
    webPreferences: {
      nodeIntegration: true
    }
  });

  win.loadFile("index.html") // To load local HTML files easily

}
于 2019-07-18T13:38:35.947 回答