I. Project technology stack: Electron+ React + React-Router + ANTD

** Electron: ** Electron is a framework for creating native desktop applications using WEB technologies such as JS, HTML and CSS. Based on Chromium and Node. js, he builds applications that can run on Mac, Windows and Linux. 2. React and React-Router are responsible for building single-page applications and implementing route jumps in this project. 3. Antd as UI framework.

Ii. Project construction

Create a React project

We use is now more mature the create – react – app scaffolding to create a react project, for more information about the scaffolding can view: facebook. Making. IO/create – fax…

Here we use the following command:

npx create-react-app my-app 
cd my-app 
npm start
Copy the code

If successful, you can open and browse the project we created at http://localhost:3000/. You can pop up the build in via NPM Run eject to see what installed dependencies there are.

2. Introduce electron

npm i electron --save-dev
Copy the code

After the installation is successful, you cannot run some commands directly. You need to do some configuration first, at least have the main.js entry file (in the root directory) that electron needs to use.

3, configuration,

① Configure the import file in package.json as follows:

Modify the startup command:

Dev here wants to follow two orders at the same time, using the | separated the two commands. Electron. –debug is the debugging command that needs to run the project and start the developer tool at the same time. The entry file will judge this command and start the specified tool.

② Preparation of main.js file

(Copy main.js from the electron demo project on Github and make some changes.) Here is the current entire main.js content

const { app, BrowserWindow } = require('electron');
const path = require('path');
let mainWindow = null;
// Check whether the second argument to the command line script contains --debug
const debug = /--debug/.test(process.argv[2]);
function makeSingleInstance () {
    if (process.mas) return;
    app.requestSingleInstanceLock();
    app.on('second-instance'.() = > {
        if (mainWindow) {
            if (mainWindow.isMinimized()) mainWindow.restore()
            mainWindow.focus()
        }
    })
}
function createWindow () {
    const windowOptions = {
        width: 400.height: 300.frame:false}; mainWindow =new BrowserWindow(windowOptions);
    mainWindow.loadURL("http://localhost:3000/");
    // mainWindow.loadURL(path.join('file://', __dirname, '/build/index.html'));
    // Receives information about the render process
    const ipc = require('electron').ipcMain;
    ipc.on('min'.function () {
        mainWindow.minimize();
    });
    ipc.on('max'.function () {
        mainWindow.maximize();
    });
    ipc.on("login".function () {
        mainWindow.maximize();
    });
    // If yes --debug opens developer tools, maximizes window,
    if (debug) {
        mainWindow.webContents.openDevTools();
        require('devtron').install();
    }

    mainWindow.on('closed'.() = > {
        mainWindow = null
    })
}
makeSingleInstance();
// Events and methods for the main app process
app.on('ready'.() = > {
    createWindow();
});
app.on('window-all-closed'.() = > {
    if(process.platform ! = ='darwin') {
        app.quit()
    }
});
app.on('activate'.() = > {
    if (mainWindow === null) { createWindow(); }});module.exports = mainWindow;
Copy the code

As above, note that the loadUrl of the main process is set to localhost:3000 to display pages running at this address.

③ Install and configure the Devtron plug-in

Use the following command to install:

npm i devtron --save-dev
Copy the code

After installation: configure in main.js, refer to the comments in the main.js file above.

4. Process communication

After the construction of the project is completed, an application problem in the combination of react project and ELECTRON will be explained here. First put forward the requirements, as shown in the figure below. We need to minimize the page window when clicking on the upper right corner of the page to minimize (the function when clicking × can be used in the same way), modify the window size when clicking on the login, and display the live broadcast page.

To do this, you need to use the Electron API, which starts with the Electron application structure, which is divided into the main process and the renderer process. This means that main.js is the main process, and a web page opened in the main process is a renderer process. The web page is the index.html in the project, and the system level interaction can be carried out directly on the Web page through the NodeJS API.If we didn’t use React, there would be no problem, but introducing electron in React would give an error. To use react, assign electron to window. Electron in advance for easy use. Add js to the head of index. HTML as shown below:

<script>global.electron = require('electron')</script>
Copy the code

At this point, recalling the requirements, we find that the UI that triggers the event is in the Web page (the React component), while the mainWindow object that we want to operate on (the page opened in the main process) is in the main process. So, try a solution that lets the Web page (the React component) communicate with the main process. The apis used to implement process communication are ipcRenderer and ipcMain.

The specific application is as follows:

import React from 'react';
import { Layout,Icon } from 'antd';
import "./UserLayout.scss";
import UserRouter from ".. /.. /router/userRouter";
const {ipcRenderer} = window.electron;
class UserLayout extends React.Component{
    closeWindow=() = >{
        window.close();
    };
    minWindow=() = >{
        ipcRenderer.send("min");
    };
    render(){
        return(
            <div className="login">
                <div className="top">
                    <div className="top-right">
                        <Icon type="minus" style={{margin:"0 8px"}} onClick={this.minWindow}/>
                        <Icon type="close" onClick={this.closeWindow}/>
                    </div>
                    <div className="top-center">Cloud live</div>
                </div>
                <div className="main">
                    <div className="main-content">
                        {UserRouter()}
                    </div>
                </div>
            </div>)}}export default UserLayout;
Copy the code

When clicked above, execute minWindow, introduce ipcRender to send a message “min”, there is corresponding ipcMain in main.js to listen, please see the following:

// Receives information about the render process
    const ipc = require('electron').ipcMain;
    ipc.on('min'.function () {
        mainWindow.minimize();
    });
Copy the code

Therefore, after the main process receives the message, it can process the window to minimize, and the login function is similar to this. The message is delivered to the main process and the page is jumped at the same time. The main process executes the window maximization after receiving the message, so the initial requirements are realized. Similarly, you can use this scenario when the component has other operations that require feedback from the main process.