Martn__
Martn__

Reputation: 23

Electron.js Error: require is not defined

I'm writing my first electron app, and I was trying to show a window when a button is clicked. I have an error message:

Uncaught ReferenceError: require is not defined at dialog.js:2

I'm using the version "electron-nightly": "^6.0.0-nightly.20190213"

here is the code:

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();
});

Is this error something about ES6+?

Upvotes: 2

Views: 1115

Answers (1)

user9717580
user9717580

Reputation:

You may have to enable Node integration in your new window (disabled by default according to the 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

}

Upvotes: 2

Related Questions