Skip to content

Exercise 1: Hello Electron! (Part 2)

David Neal edited this page May 31, 2018 · 2 revisions

Open Project in Visual Studio Code

  1. Launch Visual Studio Code
  2. Click File -> Open...
  3. Browse to project folder and click Open

Create main.js

Add a file named main.js with the following:

const electron = require( "electron" );
const { app, BrowserWindow } = electron;

let mainWindow = null;

app.on( "window-all-closed", () => {
    if ( process.platform !== "darwin" ) {
        app.quit();
    }
} );

app.on( "ready", () => {
    mainWindow = new BrowserWindow( { width: 800, height: 600 } );
    mainWindow.loadURL( `file://${ __dirname }/index.html` );

    mainWindow.on( "closed", () => {
        mainWindow = null;
    } );
} );

Create index.html

Create a file named index.html with the following:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Hello Electron</title>
</head>
<body>
    <h1>Hello from Electron!</h1>	
</body>
</html>

Update package.json

Update the main and add a "start" script to scripts.

  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "electron ."
  },

Launch the Application

From the Terminal / Command window, run:

npm run start

Bonus: Gracefully load HTML content

The BrowserWindow has a number of other events, including one named ready-to-show. This event is fired when the DOM has finished rendering. You can delay showing the window until the DOM has finished to ensure the user does not see any unstyled content. Your code might look something like this:

app.on( "ready", () => {
    mainWindow = new BrowserWindow( { width: 800, height: 600, show: false } );
    mainWindow.loadURL( `file://${ __dirname }/index.html` );
    mainWindow.once( "ready-to-show", () => {
        mainWindow.show();
    } );
    mainWindow.on( "closed", () => {
        mainWindow = null;
    } );
} );