preface

Xiaolang learned electron because he needed to hand in a software assignment for the software construction class, so he didn’t want to use Java to write it, and it couldn’t be a web page. At first, he thought of using UNIApp to write a project and package it into an APP. Then after thinking about it, he always heard that electron could use front-end pages (native/H5 / Vue/React…). Typora is made by electron. I’m curious, so I want to learn it. The following are xiaolang’s notes on learning electron, hoping to give you some help. However, the official document is relatively clear and comprehensive, you may see in the video tutorial can be used, when you type, you may find various problems, I thought that I misspelled something, a look is the official document updated…

1. Basic use

To make a desktop application, we need to get to know it quickly

1.1 Terminal Garbled Characters

Tip: Chinese garbled characters will appear in the electron control printing

Just enter CHCP 65001 on the terminal (CMD) and run

1.2 installation

/ / if no first if the node node HTTP: / / http://nodejs.cn/download/ / / in the current directory to install the latest NPM I - D electron / / install the latest global CNPM install electron - g / / Of course you can specify the version number to install NPM i-d [email protected]Copy the code

Node -v electron -v Checks whether the installation is successful

1.3 Quick Creation

Start creating a electron

  • First of all, the directory must include:package.jsonThis file
  • And then you have an entry file that I’m going to use for this exampleindex.jsFor example, but it’s usually written asmain.jsbetter
  • At the very least, you need a display GUI interface, usually the front page, or you can directly put a website

Create a new directory (project):

Initialize the package.json file

npm init
Copy the code

Write down the description. I remember I needed the description when I packed the electron

Start command write “test”: Nodemon –watch index.js –exec electron.” Nodemon –watch index.js –exec electron

Take a look at the final package.json file

/ / package. Json file

{
  "name": "electron_demo"."version": "1.0.0"."description": "\" This is a electron demo\"."main": "index.js"."scripts": {
    "test": "nodemon --watch index.js --exec electron ."
  },
  "author": ""."license": "ISC"
}

Copy the code

My directory contains the following files

Electron is divided into two processes the main process and the renderer process

The index.js file is the main process

That’s the official line

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

function createWindow () {   
  // Create a browser window
  const win = new BrowserWindow({
    width: 800.height: 600.webPreferences: {
      nodeIntegration: true}})// And load index.html for your application
  win.loadFile('index.html')

  // Open the developer tool
  win.webContents.openDevTools()
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Parts of the API can only be used after the ready event is triggered.
app.whenReady().then(createWindow)

// Quit when all windows are closed.
app.on('window-all-closed'.() = > {
  // On macOS, unless the user explicitly exits with Cmd + Q,
  // Otherwise, most apps and their menu bar remain active.
  if(process.platform ! = ='darwin') {
    app.quit()
  }
})

app.on('activate'.() = > {
  // On macOS, when you click the Dock icon and no other Windows open,
  // Usually a window is recreated in the application.
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})

// In this file you can include the rest of your app's specific main process
// code. It can also be split into several files and imported with require.
Copy the code

I saw other people write something like this

const { app, BrowserWindow } = require('electron')
let win
// Listen for the creation window when the electron load completes, etc
app.on('ready'.function () {
    // Create a window setting property
    win = new BrowserWindow({
    //fullscreen: true //fullscreen
    //frame: false, // make the desktop application have no border so that the menu bar disappears
    resizable: false.// The user is not allowed to change the window size
    width: 800.// Set the window width and height
    height: 600.icon: iconPath,     // The title bar icon when the application is running
    minWidth: 300.// Minimum width
    minHeight: 500.// Minimum height
    maxWidth: 300.// Maximum width
    maxHeight: 600.// Maximum height
    // Set the preferences
    webPreferences: {backgroundThrottling: false.// Set the application to run properly in the background
      nodeIntegration:true.// Set the API that can use nodejs on the page
      contextIsolation: false.// Turn off the warning message
      //preload: path.join(__dirname, './preload.js')}})// Let the main process load an index.html
  win.loadFile('index.html')
  // Set it to the top layer
  //win.setAlwaysOnTop(true)
  // win.loadurl (' www.baidu.com ') allows the main process to open a file or a link
  // Listen for window closing events
  win.on('closed'.() = >{
      / / release the win
      win = null})})// All Windows are closed
app.on('window-all-closed'.() = > {
    
    console.log('All the Windows are closed.')})Copy the code

Index. HTML is a rendering process, which is basically a front end page where you write stuff, which is pretty much a GUI

<! DOCTYPEhtml>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>electron test</title>
  </head>
  <body>
    electron demo
    <script></script>
  </body>
</html>

Copy the code

This creates an interface using NPM test, which comes from package.json script

2. Remote module

In the rendering process (e.g. index.html loaded js files that use remote to use BrowserWindow attributes)

Using the remote module, you can call methods on the main process object

2.1.electron14.0Previous versions used

To call the remote module, add the enableRemoteModule: true parameter to the main process window

const { app, BrowserWindow } = require('electron')
app.on('ready'.function () {
  let win = new BrowserWindow({
    width: 800.height: 600.webPreferences: {
      // Add here
      enableRemoteModule: true.nodeIntegration: true.contextIsolation: false,
    },
  })
  win.loadFile('index.html')
  // All Windows are closed
  app.on('window-all-closed'.() = > {
    / / release the win
    win = null
    console.log('All the Windows are closed.')})})Copy the code

And then in the render process, I’m going to embed js directly

<! DOCTYPEhtml>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>electron test</title>
  </head>
  <body>
    electron demo
    <button id="btn">Add a new window</button>
    <script>
      const { log } = console
      // Import BrowserWindow in remote
      const { BrowserWindow } = require('electron').remote

      const btn = document.getElementById('btn')
      btn.onclick = () = > {
        let newWin = new BrowserWindow({
          width: 800.height: 600,})// newWin.loadURL('www.baidu.com')
        win.loadFile('index2.html')

        newWin.on('close'.() = > {
          newWin = null})}</script>
  </body>
</html>

Copy the code

Click the button here to create a new window

2.2.electron14.0Version API Changes

But there are versions of it, and it bothered me for a long, long time… Finally I looked at the document 14.0 and changed it. I used 15…

1. You have to install Remote yourself

npm i -D @electron/remote
Copy the code

2. Import it from the main process

app.on('ready'.function(){
	require('@electron/remote/main').initialize()
})
Copy the code

3. In the rendering process

// To introduce remote
const { BrowserWindow } = require('@electron/remote') 
Copy the code

3. Create a system menu

1. Create a menu.js file

// 1. Import Menu in electron
const { Menu } = require('electron')

// 2. Create a menu template. Each object in the array is a menu
const template = [
  {
    label: 'Menu one'.// submenu indicates the next-level menu
    submenu: [{label: 'Submenu 1' ,
          // Add shortcut keys
          accelerator: 'ctrl+n'
      },
      { label: 'Submenu two' },
      { label: 'Submenu three' },
      { label: 'Submenu 4'},],}, {label: 'Menu two'.// submenu indicates the next-level menu
    submenu: [{label: 'Submenu 1' },
      { label: 'Submenu two' },
      { label: 'Submenu three' },
      { label: 'Submenu 4'},],},]// 3. Create a menu from the template
const myMenu = Menu.buildFromTemplate(template)

// 4. Set to application menu
Menu.setApplicationMenu(myMenu)

Copy the code

Accelerator: ‘CTRL + N’ can specify shortcut keys for the menu

2. Write a random page

<! DOCTYPEhtml>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Custom menu</title>
  </head>
  <body>Custom menu<script></script>
  </body>
</html>

Copy the code

3. Write the main. Js

// 1. Introduce the electron
const { app, BrowserWindow } = require('electron')
// Define a window
let win = null
// 2. Introduce custom menus
require('./menu')

// 3
app.on('ready'.function () {
  win = new BrowserWindow({
    width: 800.height: 600,})// Open the console
  win.webContents.openDevTools()
  win.loadFile('./index.html')
  // 4. Listen for window closing events
  win.on('close'.() = > {
    win = null})})Copy the code

NPM test launch

4. Add events to the menu

For example, add a click event to a submenu and create a new window

// 1. Import Menu in electron
const { Menu, BrowserWindow } = require('electron')

// 2. Create a menu template. Each object in the array is a menu
const template = [
  {
    label: 'Menu one'.// submenu indicates the next-level menu
    submenu: [{label: 'Submenu 1'.// Add click events
        click: () = > {
          Create a new window
          let sonWin = new BrowserWindow({
            width: 200.height: 200,
          })
          sonWin.loadFile('./index2.html')
          // Empty for shutdown
          sonWin.on('close'.() = > {
            sonWin = null})}}, {label: 'Submenu two' },
      { label: 'Submenu three' },
      { label: 'Submenu 4'},],}, {label: 'Menu two'.// submenu indicates the next-level menu
    submenu: [{label: 'Submenu 1' },
      { label: 'Submenu two' },
      { label: 'Submenu three' },
      { label: 'Submenu 4'},],},]// 3. Create a menu from the template
const myMenu = Menu.buildFromTemplate(template)

// 4. Set to application menu
Menu.setApplicationMenu(myMenu)

Copy the code

rendering

The Developer Tools above, like chrome/ Edge, can be called from the menu bar, View -> Toggle Developer Tools, or Ctrl + Shift + I to debug the page

5. Use node.js modules/apis

Write an example of reading and writing a file

WebPreferences must add nodeIntegration: true, contextIsolation: false when creating the main window

This allows some of Node’s syntax to be used in the rendering process

main.js

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

let mainWindow = null

app.on('ready'.() = > {
  // // Create a new window
  mainWindow = new BrowserWindow({
    width: 800.height: 600.webPreferences: {
      nodeIntegration: true.// Whether to integrate Nodejs, remove the preloaded JS, found also can run
      contextIsolation: false,}})// Load the render file
  mainWindow.loadFile('./main.html')
  // Empty variables after the window closes
  mainWindow.on('close'.() = > {
    mainWindow = null})})Copy the code

Main.html The main render file

<! DOCTYPEhtml>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Read and write file tests</title>
  </head>
  <body>
    <button onclick="readFile()">Read the file</button>
    <button onclick="writeFile()">Written to the file</button>
    <p id="show_file_content">The page content</p>
    <script src="./index.js"></script>
  </body>
</html>

Copy the code

Index.js loads the required JS

As you can see, in the renderer process, which is loaded with index.js in main.html, you can use the WebAPI docment.getelementById and use the node module to mix it up

// Import the node module
const fs = require('fs')
const path = require('path')
const { log } = console

// Get the dom of the file display
const showContent = document.getElementById('show_file_content')

// Read the file
function readFile() {
  console.log('Read file')
  fs.readFile(path.join(__dirname, '/test.txt'), (err, data) = > {
    if (err) {
      throw new Error(err, 'File reading failed')
    }
    showContent.innerText = data
  })
}
// What needs to be written
const content = 'Today is the second day of National Day, studying electron'

// Write to the file
function writeFile() {
  fs.writeFile(
    path.join(__dirname, '/test.txt'),
    content,
    'utf8'.(err, data) = > {
      if (err) {
        return new Error(err, 'File reading failed')
      }
      log('Write file successful')})}Copy the code

TXT for testing

Today is the second day of National Day, studying electronCopy the code

Project catalog

rendering

6. Set no border

You can create Windows with no borders, and the menu with them is gone

let win = new BrowserWindow({
    frame: false.// Leave the desktop app without borders so that the menu bar disappears
    width: 800.// Set the window width and height
    height: 600,})Copy the code

The menu is still there, you can still use shortcuts to call out the menu, you can delete the menu win.removemenu ()

How do I drag Windows without a menu bar

In THE CSS you can set which drags are allowed and which drags are not allowed

Such as body {- its – app – region: drag | no – drag; }

Image: No border, drag and drop in body Settings

7. System tray

It should be clear to everyone that when we close an application, it’s actually closed, but it’s not completely closed, it’s just hidden, and some of it is in the system tray. So how do you set up the system tray at Electron

Official documentation: Tray

Main process index. Js

In electron here I added the system tray at the beginning, of course you can listen when the window is closed while creating the tray

// To create menus under Tray, Menu, etc.,nativeImage creates icon icon
const { app, BrowserWindow, Tray, Menu, nativeImage } = require('electron')
const path = require('path')
let win, tray
app.on('ready'.function () {
  win = new BrowserWindow({
    width: 800.height: 600,})I'm using a PNG here
  const icon = nativeImage.createFromPath(
    path.join(__dirname, '/static/icon.png'))// Instantiate a tray object, passing in the tray icon
  tray = new Tray(icon)
  // Move to tray prompt
  tray.setToolTip('electron demo is running')
  // Titlle can also be set
  tray.setTitle('electron demo')

  // Listen for the tray right-click event
  tray.on('right-click'.() = > {
    // Right-click the menu template
    const tempate = [
      {
        label: 'No operation'}, {label: 'exit'.click: () = > app.quit(),
      },
    ]
    // Create a Menu through Menu
    const menuConfig = Menu.buildFromTemplate(tempate)
    // Let our write tray right-click menu replace the original
    tray.popUpContextMenu(menuConfig)
  })
  // Listen for the tray click event
  tray.on('click'.() = > {
    // Here to control the window display and hide
    if (win.isVisible()) {
      win.hide()
    } else {
      win.show()
    }
  })
  win.loadFile('index.html')})// All Windows are closed
app.on('window-all-closed'.() = > {
  / / release the win
  win = null
  console.log('All the Windows are closed.')})Copy the code

rendering

8. Interprocess communication

Electron requires communication between the main process and the renderer process

Official documents:

ipcMain

ipcRenderer

webContents

The main thread to the renderer thread is sent via webcontents. send –> ipcrenderer. on to listen

The renderer thread to the main thread is listened on by sending ipcrenderer. send –> ipcmain. on

8.1. Main process to renderer process

webContents.send(channel, ... args)

  • channel String
  • . args any[]

Main process mian. Js

Send the message in the main process using webcontents.send

/ / main process
const { app, BrowserWindow } = require('electron')
let win
// Listen for the creation window when the electron load completes, etc
app.on('ready'.function () {
  // Create a window
  win = new BrowserWindow({
    width: 800.// Set the window width and height
    height: 600.// Set the preferences
    webPreferences: {
      enableRemoteModule: true.nodeIntegration: true.// Set the API that can use nodejs on the page
      contextIsolation: false.// Turn off the warning message}})// to the render thread
  setTimeout(() = > {
    win.webContents.send('mainMsg'.'I'm a message from the main thread.')},3000)
  // Let the main process load a main.html
  win.loadFile('main.html')})// All Windows are closed
app.on('window-all-closed'.() = > {
  / / release the win
  win = null
  app.quit()
  console.log('All the Windows are closed.')})Copy the code

The render process main.html is linked to a render

Use ipcrenderer.on in the render thread to listen

ipcRenderer.on(channel, listener)

  • channel String
  • listener Function

Listen for a channel and use listener(Event, args…) when a new message arrives. Call the listener.

Ipcrenderer.once (channel, listener)

Add a one-time listener function for this event. This listener will be called the next time a new message is sent to a channel and then deleted

<! DOCTYPEhtml>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Communication test</title>
  </head>
  <body>Communication test<p id="receive">Receive information</p>
    <script src="./render.js"></script>
  </body>
</html>

Copy the code
// Render process

/ / introduce ipcRenderer
const electron = require('electron')
const { ipcRenderer } = require('electron')
const { log } = console

log(ipcRenderer)
ipcRenderer.on('mainMsg'.(event, task) = > {
  log(task)
  document.getElementById('receive').innerText = task
})

Copy the code

rendering

8.2. Render process to main process

Render. Js render thread to send ipcrenderer.send

ipcRenderer.send(channel[, arg1][, arg2][, ...] )

  • channel String
  • arg(optional)

Ipcrenderer. sendSync(channel[, arg1][, arg2][,… )

<! DOCTYPEhtml>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Communication test</title>
  </head>
  <body>Communication test<p id="receive">Receive information</p>
    <button onclick="sendMain()">Sends a message to the main thread</button>
    <script src="./render.js"></script>
  </body>
</html>

Copy the code
const electron = require('electron')
const { ipcRenderer } = require('electron')

/ /...

function sendMain() {
  ipcRenderer.send('task'.'Exit program')}Copy the code

Js main process in the ipcmain. on to listen, here exit the program

ipcMain.on(channel, listener)

  • channel String
  • listener Function

Listen on a channel. When a new message arrives, the listener(Event, args…) Call the listener.

There is also ipcmain. once(channel, listener) to add a one-time listener function to the event. This listener is invoked only the next time a message arrives at a channel, after which it is deleted.

const { app, BrowserWindow, ipcMain } = require('electron')
// Listen for the creation window when the electron load completes, etc
app.on('ready'.function () {
  / /...
})

ipcMain.on('task'.(event, info) = > {
  if (info === 'Exit program') {
    app.quit()
  }
})

Copy the code

rendering

In this way, IT is convenient for me todo some window interaction, such as todoList. When the time is up, a new window will pop up in the lower right corner to remind me

8.3 Render Process to Render process

ipcRenderer.sendTo(webContentsId, channel, ... args)

  • webContentsId Number
  • channel String
  • . args any[]

Send a message through a channel to a window with a webContentsId.

The premise is to know the ID of the corresponding renderer process

It is also possible to use the main process as a staging post before sending to other renderers

9.Vue + Electron

So how does Vue use Electron packing? After all, the original purpose of learning is to turn the Vue project into a desktop application. The previous methods are all native, so read on

9.1 You need to have a Vue project

If not, create a VUE project using the Vue UI/or create it directly from the command line using vue Create

vue ui
Copy the code

I’m sure you can, but I’m just going to create a simple vue UI here, so you can skip it

Default open a 8000 port service, a visual UI interface will come out

Select More in the lower left corner -> Project Manager

create

Select a directory and create it here

Fill in some basic information, package management I use NPM here, and then the next step

Select presets, I’m here the player moves

I’m going to choose which plug-ins I need by default, because it’s a simple example

Choose Vue version 2.x or 3 according to your habit, usually write what to choose, the following options I choose the standard

Create a project

I’m not going to save the preset here, and then it’s a long wait

Run the change project after it is created

Start the project

You get a default page that looks like this

Okay, so we’re done creating the project. Move on

9.2 addelectronThe plug-in

Go to Plug-ins –> Add Plug-ins search vuE-cli-plugin-electron – Builder and install the first one

I chose Electorn 13.0.0 by default

After the installation is complete, it will appear in the installed plug-in

You can also install it from the command line

vue add electron-builder
Copy the code

9.3 run

Run the following command from the command line under the current VUE project

npm run electron:serve
Copy the code

Good. It’s working

9.4 package.json background.js

Look at the package.json file and see where the main process file is

The main process file is background.js, which is under the Vue project/SRC /

'use strict'

import { app, protocol, BrowserWindow } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
constisDevelopment = process.env.NODE_ENV ! = ='production'

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app'.privileges: { secure: true.standard: true}}])async function createWindow() {
  // Create the browser window.
  const win = new BrowserWindow({
    width: 800.height: 600.webPreferences: {
      
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION
    }
  })

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if(! process.env.IS_TEST) win.webContents.openDevTools() }else {
    createProtocol('app')
    // Load the index.html when not in development
    win.loadURL('app://./index.html')}}// Quit when all windows are closed.
app.on('window-all-closed'.() = > {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if(process.platform ! = ='darwin') {
    app.quit()
  }
})

app.on('activate'.() = > {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready'.async() = > {if(isDevelopment && ! process.env.IS_TEST) {// Install Vue Devtools
    try {
      await installExtension(VUEJS_DEVTOOLS)
    } catch (e) {
      console.error('Vue Devtools failed to install:', e.toString())
    }
  }
  createWindow()
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message'.(data) = > {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM'.() = > {
      app.quit()
    })
  }
}

Copy the code

If the main process file above looks familiar, you can do the same things you did before, using Node to mix up some functionality

9.5 packaging

Above we just run out, handed in the software, the teacher will not also deliberately to match the environment, and then NPM run electron:serve it, obviously is impossible, then we continue to pack into an executable file EXE

Command line Run the following command

npm run electron:build
Copy the code

Problems with packaging

I had a really bad time packing… I’ve been looking around and it turns out there’s a problem with electron

My suggestion is to delete electron in the node_modules directory

Install electron with CNPM

If no CNPM is installed first

Install CNPM globally

npm install -g cnpm --registry=https://registry.npm.taobao.org
Check whether the installation was successful
cnpm -v
Copy the code

Reinstall electron

cnpm i electron
Copy the code

packaging

npm run electron:build
Copy the code

When the packing is complete, the packed file is placed in dist_electron under the project

9.6 installation

Double click to install it automatically

An app icon appears on the desktop

9.7 the custom

Click to view no problem, but is not too low, a click is automatically installed, and use the default icon

Installing the Packing Tool

cnpm i electron-builder --D
Copy the code

9.7.1. Find one firsticonThe picture

There seems to be a plugin that can turn images into ICONS of various sizes

Install it so you don’t have to transfer pictures to your website

cnpm i electron-icon-builder 
Copy the code

You need to add the build-icon directive to scripts in package.json

Kakarotte can modify this picture by himself

Output is the output folder


  "scripts": {
    "build-icon": "electron-icon-builder --input=./public/longzhu.jpg --output=build --flatten"
  },
Copy the code

Command line input

npm run build-icon
Copy the code

After the build is complete, images of different sizes are generated

9.7.2. Vue. Config. Js

Because the plug-in we installed earlier was vuE-cli-plugin-electric-Builder, not electric-Builder

Electron – Builder packages normal projects, and build configurations are written directly in package.json

The build configuration of vue-cli-plugin-electric-Builder needs to be configured in vue.config.js under the project root directory

If no, create one

module.exports = {
  pluginOptions: {
    electronBuilder: {
      builderOptions: {
        appId: "com.test.app".productName: "Lang".// The project name, which is also the generated installation file name, namely ademo.exe
        copyright: "Copyright © 2021".// Copyright information
        directories: {
          output: "./dist" // Output file path
        },
        win: {
          // Win-related configuration
          icon: "./build/icons/icon.ico".// the current icon is in the root directory. Note that there are two pits
          target: [{target: "nsis".// Use nsis to make the installation program, package the file suffix exe
              arch: [
                "x64"./ / 64
                "ia32" / / 32 bits]]}},nsis: {
          oneClick: false.// One-click setup
          language: "2052".// Install language
          perMachine: true.// Apply to all users
          allowToChangeInstallationDirectory: true // The user can select the path}}}}};Copy the code

9.7.3. Perform packaging

npm run electron:build
Copy the code

OK, packing success!

Possible problems

The way to package is not smooth, packaging failed at this step, because when packaging to download some dependencies, and then the download failed

Solution 1: Ladders

Solution 2: Look at this

Packed things

The package is placed in our previously configured build Output: “./dist” // output file path

You can see that the icon has changed

We can now customize the installation folder

Well, the basic packaging work is done, you can write your own software, here is a simple application teaching

conclusion

Electron is really good, I suggest you to read the official document more when learning. Although there are many incomplete translations in the official document, it doesn’t affect our enthusiasm to learn it. I feel that the version is iterated quickly, and the official document seems to be too many and messy

Electron official Document

Past wonderful

Can’t Vue3 yet? A quick introduction to notes

Not TS yet? Get you started with TypeScript quickly

Quick start Vuex to easy writing Vuex

From understanding to in-depth virtual DOM and implementation of diff algorithm

Write a simple VUE response to take you to understand the principle of response

From using it to implementing your own simple Vue Router look at this

The essential basics of the front-end interview, although little but you can’t help but know