Know the Electron

Electron lets you use Web development techniques to develop cross-platform desktop applications. It is led and open sourced by Github, and is used to develop the familiar Atom and VSCode editors.

Electron is a hybrid of the Node.js and Chromium browser. The Chromium browser displays the Web page as the GUI of the application and interacts with the operating system via Node.js. When you operate in a window in Electron, you are actually operating on a web page. Web pages interact with the operating system via Node.js when you need to do something with the operating system.

The advantages of developing desktop applications in this way are as follows:

  • To lower the development threshold, you only need to master Web development techniques and Node.js. A large number of Web development techniques and ready-made libraries can be used in Electron.
  • Since both Chromium browser and Node.js are cross-platform, Electron can write code to run on different operating systems.

When you run Electron, you start a main process. The main process is started by executing an entry JavaScript file in Node.js, which contains the following contents:

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

// Keep a global reference to the window object, if you don't,
// When the JavaScript object is garbage collected, the window is automatically closed
let win

// Open the main window
function createWindow() {
  // Create a browser window
  win = new BrowserWindow({ width: 800.height: 600 })

  // Load the app's index.html
  const indexPageURL = `file://${__dirname}/dist/index.html`;
  win.loadURL(indexPageURL);

  // This event is raised when the window is closed
  win.on('closed', () = > {// Unreference the window object
    win = null})}// Electron calls this function when the browser window is created.
app.on('ready', createWindow)

Exit when all Windows are closed
app.on('window-all-closed', () = > {// On macOS, unless the user exits definitively with Cmd + Q
  // Otherwise most applications will remain active
  if(process.platform ! = ='darwin') {
    app.quit()
  }
})
Copy the code

After the main process is started, it always resides in the background, and the window you see and operate is not the main process, but the window child started by the main process.

An application has a series of life cycle events from startup to exit. The electron.app.on() function is used to listen for life cycle events and react at a specific time. For example, in app.on(‘ Ready ‘) event, BrowserWindow is used to display the app’s main window. See the BrowserWindow API documentation for details.

The startup window is actually a web page that loads the web address passed in loadURL when it starts. Each window is a separate web page process, and communication between Windows requires the main process to pass messages.

Generally speaking, developing Electron is similar to developing Web applications. The difference lies in that Electron runs in a built-in browser and Node.js API. In addition to the API provided by the browser, You can also use the API provided by Node.js.

Access Webpack

Then do a simple Electron app, which requires a main window to be displayed when the app starts up. There is a button in the main window. Click the button to display a new window and use React to develop the web page.

Since each window in Electron corresponds to a web page, two web pages need to be developed, namely the index.html of the main window and the login.html of the newly opened window. That is to say, the project consists of two single-page applications. This is very similar to the project in 3-10 managing multiple single-page applications. Let’s transform it into a Electron application.

The changes are as follows:

  • Create a new entry file for the main process in the project root directorymain.js, the content is the same as mentioned above;
  • The code for the main window page is as follows:
import React, { Component } from 'react';
import { render } from 'react-dom';
import { remote } from 'electron';
import path from 'path';
import './index.css';

class App extends Component {

  // When the button is clicked
  handleBtnClick() {
    // The URI of the page corresponding to the new window
    const modalPath = path.join('file://', remote.app.getAppPath(), 'dist/login.html');
    // Size of the new window
    let win = new remote.BrowserWindow({ width: 400.height: 320 })
    win.on('close'.function () {
      // Clear resources when the window is closed
      win = null
    })
    // Load the page
    win.loadURL(modalPath)
    // Display window
    win.show()
  }

  render() {
    return (
      <div>
        <h1>Page Index</h1>
        <button onClick={this.handleBtnClick}>Open Page Login</button>
      </div>
    )
  }
}

render(<App/>.window.document.getElementById('app'));
Copy the code

The key part is to use the API provided in the electron library to open a new window in the button click event and load the address of the web page file.

Now that the code in the page section has been modified, let’s change the code in the build area. Here the build needs to do the following:

  • Build two web pages that can run in the browser, corresponding to the interface of two Windows;
  • Because JavaScript code in a web page may call the Node.js native module orelectronModules, that is, the output code depends on these modules. But because these modules are built in, the code you build can’t package them in.

This is easy to do because Webpack has built-in support for Electron. Just add a line of code to the Webpack configuration file like this:

target: 'electron-renderer'.Copy the code

This configuration was mentioned in other configuration item 2-7 -Target, which means to have Webpack build the JavaScript code for the Electron rendering process, i.e. the web page code required for the two Windows.

After all the above modifications are completed, the Webpack construction is executed again, and the corresponding code required by the web page is output to the dist directory under the root directory of the project.

In order to run as Electron, you also need to install new dependencies:

Install the Electron execution environment into the project
npm i -D electron
Copy the code

After the installation is successful, run electron in the project directory and you should see the desktop application launch successfully.

This example provides the complete code for the project

Easy to Understand Webpack online reading link

Read the original