【问题标题】:Electron.js Error: require is not definedElectron.js 错误:未定义要求
【发布时间】:2019-08-01 04:48:03
【问题描述】:

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

未捕获的引用错误: 要求未定义 在 dialog.js:2

我使用的是“electron-nightly”版本:“^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);

index.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>

dialog.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+ 的吗?

【问题讨论】:

    标签: javascript electron


    【解决方案1】:

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

    index.js

    function main() {
    
      win = new BrowserWindow({
        width: 500,
        height: 400,
        webPreferences: {
          nodeIntegration: true
        }
      });
    
      win.loadFile("index.html") // To load local HTML files easily
    
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-08
      • 2022-12-11
      • 1970-01-01
      • 2017-01-20
      • 2018-07-14
      • 2019-03-13
      • 1970-01-01
      • 2021-08-23
      • 1970-01-01
      相关资源
      最近更新 更多