Take the first step in learning how to create native desktop applications with Electron. We'll set up a package.json, create an npm start script to launch our app in development, and create a browser window and load a local HTML file into it.
An important concept to understand about Electron is it's multi-process architecture. The main process creates web pages by creating
BrowserWindow instances, manages application lifecycle events, and more. Each
BrowserWindow instance runs the web page in its own renderer process.
To install Electron on our machine for development on our machine, first, let's create a package.json. We'll run npm init and pass the y flag to get all the defaults. Let's run npm install electron --save-dev.
Now, let's add an npm start script for launching our app. Open package.json in the scripts field, here, we'll add start. We execute our application with Electron and we'll pass index.js which would be the entry point for our application.
Let's create index.js now. Let's require apps and browser window from Electron, plus, we'll require tasks from node.js core. We'll also create a reference to our main window up here.
We define it up here at the top level, so that it never goes out of scope in a function closure. If it does go out of scope, we risk having our browser window garbage collected and destroyed. The app module in Electron exposes various application lifecycle events, we'll define an onReady handler for our application.
In here, we'll create our browser window. We can't create our browser window instance before this event has been called. Let's tell our browser window just to load an HTML file. I'll call mainWindow.loadURL, and we'll use path.join to construct an absolute file path to our file.
We'll pass the file protocol, because it's a local HTML file. Then, we'll pass the dirname variable which is a string that represents our current working directory. This is passed to every node.js module automatically.
Then, we'll pass index.html which will be our file name. Next, let's add our HTML file. Create our index.html, and we'll just add some quick dummy HTML here. Let's test it out and make sure it works.
We'll run our start scripts with npm run start, and here it is, it's working. This is the browser window we created, and this is created in the main process. Then, this is the HTML file that we created. We can see our HTML is getting loaded, and that's getting run in the renderer process.