Document | Electron

Initialize the project

The React create-react app initialization project is used here.

Adding dependencies

Root directory to add. NPMRC file

sass_binary_site=https://npm.taobao.org/mirrors/node-sass/
electron_mirror=https://npm.taobao.org/mirrors/electron/
registry=https://registry.npm.taobao.org
disturl=https://npm.taobao.org/dist
Copy the code

Install YARN Add -d cross-env CONCURRENTLY electron electron-Builder

Create the electron entry file

Create electron. Js under public

// Introduce electron and create a Browserwindow
const {app, BrowserWindow, ipcMain, Menu } = require('electron')

// Keep a global reference to the window object to avoid automatic window closure when JavaScript objects are garbage collected.
let mainWindow;

const template = [
  {
    label: 'edit'.submenu: [{label: 'cut'.accelerator: 'CmdOrCtrl+X'.role: 'cut'
      },
      {
        label: 'copy'.accelerator: 'CmdOrCtrl+C'.role: 'copy'
      },
      {
        label: 'paste'.accelerator: 'CmdOrCtrl+V'.role: 'paste'
      },
      {
        label: 'all'.accelerator: 'CmdOrCtrl+A'.role: 'selectall'}]}, {label: 'look at'.submenu: [{label: 'overloaded'.accelerator: 'CmdOrCtrl+R'.click: function (item, focusedWindow) {
          if (focusedWindow) {
            After reloading, refresh and close all secondary forms
            if (focusedWindow.id === 1) {
              BrowserWindow.getAllWindows().forEach(function (win) {
                if (win.id > 1) { win.close(); }}); } focusedWindow.reload(); }}}, {label: 'Switch developer Tools'.accelerator: (function () {
          if (process.platform === 'darwin') {
            return 'Alt+Command+I';
          } else {
            return 'Ctrl+Shift+I';
          }
        })(),
        click: function (item, focusedWindow) {
          if(focusedWindow) { focusedWindow.toggleDevTools(); }}}]}]; ipcMain.on('min', () => mainWindow.minimize());
ipcMain.on('max', () = > {if (mainWindow.isMaximized()) {
    mainWindow.unmaximize();
  } else{ mainWindow.maximize(); }}); ipcMain.on('show', () => {
  mainWindow.show();
  mainWindow.focus();
});

function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 1050.height: 700.minHeight:700.minWidth:1050.webPreferences: {
      nodeIntegration: true.webSecurity: false  // false allows cross-domain
    },
    // frame:false, // Hide status bar
    // titleBarStyle: 'hidden' // MAC hides the status bar
  })

  // The development environment uses HTTP. The production environment uses file
  if (process.env.NODE_ENV === 'development') {
    mainWindow.loadURL('http://localhost:3000/');
    // Open the developer tool, not by default
    mainWindow.webContents.openDevTools()
  } else {
    mainWindow.loadURL(`file://${__dirname}/index.html`);
  }


  The following events are emitted when closing the window.
  mainWindow.on('closed'.function () {
    mainWindow = null})}// This method is called when Electron has completed initialization and is ready to create a browser window
app.on('ready', ()=>{
  createWindow();
  
  const menu = Menu.buildFromTemplate(template);
  Menu.setApplicationMenu(menu);
})

Exit the application when all Windows are closed.
app.on('window-all-closed'.function () {
  // In macOS, apps and menu bars are always active unless the user presses' Cmd + Q 'to exit explicitly.
  if(process.platform ! = ='darwin') {
    app.quit();
  }
})

app.on('activate'.function () {
  // In macOS, when you click the Dock icon and no other application window is already open, you usually rebuild a window in the application
 if (mainWindow === null) {
   createWindow()
 }
})

app.on('before-quit', (e) => {
  mainWindow = null;
});
Copy the code

Package WEB projects as local projects with absolute paths

Configure package.json under React

  1. add"main": "./public/electron.js"
  2. Configure the package file path to the absolute path under React"homepage": "."

Under VUE, vue.config.js is created in the root directory

module.exports = {
 // Basic path
 publicPath: '/'.// Output file directory
 outputDir: 'dist'.// webpack-dev-server configuration
 devServer: {
     port: 3000,}}Copy the code

Add the Electron packing configuration

Nsis is configured for installation options.

Modify the scripts

. "main": "./public/electron.js", "homepage": ".", "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject", "ele-start": "cross-env NODE_ENV=development electron .", "pc": "concurrently \"yarn start\" \"yarn ele-start\"", "ele-build": "electron-builder --win --x64" }, "build": { "productName": "XXXX", "appId": "org.XXXX.app", "mac": { "target": [ "dmg", "zip" ] }, "win": { "icon": "./public/icon.ico", "target": [ "nsis" ] }, "nsis": { "oneClick": false, "perMachine": true, "allowElevation": true, "allowToChangeInstallationDirectory": true, "createDesktopShortcut": true, "createStartMenuShortcut": true, "shortcutName": "app-name" } }, ......Copy the code

run

After the React program is loaded, press Ctrl+R to refresh the electron application content. The vacuum application content is displayed.

packaging

Yarn Build packages the React project, and yarn ele-build packages the web project into a desktop installation package.