In the last article, we introduced the basics of electron, got you started on electron, and taught you how to write a complete practical case. Here we will continue to introduce the packing and automatic updating of electron based on this project.

Generated icon

Before you package your application, prepare an icon for your application as an install package icon. Different operating systems require different formats of ICONS. The Mac icon format is ICNS, and the Windows icon format is ICO.

The icon can be generated with the help of the electron icon-Builder.

  • First, prepare one1024 * 1024 PNGImage, put the image in the project folder, we’ll put it hereTasky/public folderIn the.

  • Install the electron – icon – builder:

    npm i electron-icon-builder --D

  • Add directive to package.json scripts:

    "build-icon": "electron-icon-builder --input=./public/icon.png --output=build --flatten"

  • Running NPM run build-icon generates a series of icon files in the Build folder for packaging.

Packaging application

There are two commonly used packing tools in the Electron ecology: Electron – Builder and Electron -packager.

The electron- Builder is more flexible and widely used. Next, we use the electron- Builder for packing.

The installation

npm i electron-builder --D
Copy the code

configuration

There are mainly a variety of configurations using the electron Builder package, which supports two configurations:

  1. inpackage.jsonaddbuildFields:
"build": {
  "appId": "your.app.id"
}
Copy the code
  1. Specifies a configuration file to which configuration items are written. The default is electronic-Builder.yml in the project root directory.
AppId: "your app. Id"Copy the code

In daily development, package.json is a common configuration method, and we mainly use this method.

Basic configuration

"Build ": {"appId": "this.is.tasky", "productName":" tasky", "Copyright ": "Copyright © 2021 Alaso", "Directories ": {"buildResources": "build", // specify the static resources required by the package, default is build" output": "dist", // the directory generated by the package, default is dist}},Copy the code

The build folder holds the static files that the Electron Builder requires by default during the packing process, such as the icon file we generated above; The dist folder holds the various files generated by the package.

  1. inpackage.jsonthescriptsAdd directive:"pack": "electron-builder"
  2. runnpm run pack

Based on the above configuration, the electron- Builder packages the default files based on the current operating system. For example, on Windows, the package results are as follows:

Platform-related configurations

The electron- Builder automatically identifies the current operating system and displays the corresponding installation package. This also means that if you want to generate exe\ mSI, you need to do it on Windows, and if you want DMG, you need to do it on Mac.

The electron Builder configuration options include a number of OS related configurations that allow you to customize the package for different platforms. The following uses Windows and Mac as an example to describe some common platform-related configurations.

  1. Windows
"build": { ... "Win" : {" target ":" the msi ", "nsis"], / / install package format, default is "nsis" icon ":" "Build/ICONS /icon.ico", "target" value "nsis", the package is the exe file //nsis is the Windows installation package maker program, "Nsis ": {"oneClick": false, // whether to install oneClick, default is true "language": "2052", / / install, 2052 Chinese "perMachine" : true, / / for all users of the current system to install the application "allowToChangeInstallationDirectory" : True // Allow the user to select the installation directory}}Copy the code

2. Mac

. "Build" : {" MAC ": {" target" : "get", "zip"], / / install package format, default is "get" and "zip" "category" : "Public. App-category. Utilities", "DMG ": {"background": "public. "Build /icon /icon.icns", "build/ ICONS /icon.icns", "iconSize": 100, "contents": [/ / install ICONS in the installation window coordinates information {" x ": 380," y ": 180," type ":" the link ", "path" : "/ Applications"}, {" x ": 130," y ": 180," type ": }] "file", "window" : {/ / the size of the installation window "width" : 540, "height" : 380}}}Copy the code

Which files will be packed into the installation package

In the generated folder, there will be an app.asar, which is the main business file compression package of the Electron application. To know which files in the project are packed into the installation package, you can decompress app.asar to see.

To decompress app.asar, you need to use the ASAR tool. First install: NPM I asar -g.

Then switch to the directory containing app.asar and run: asar extract app.asar./app-folder.

For Windows, app.asar is located in the tasky\dist\win-unpacked\resources directory. When unpacked, you can see the contents of the app-folder as follows:

As you can see, this is basically all the files in the project (except the package-lock.json\.gitignore \ build folder), plus node_modules.

For node_modules, not everything in node_modules is packaged into the installation package, only dependencies in the package.json field in dependencies, not in the devDependencies field. This is the only rule, regardless of whether the project actually uses dependencies.

In order to reduce the size of the installation package, it is recommended that all external packages used in the rendering process be installed in devDependencies, and then webPack the external package code together with the business code, which will be covered in more detail in a later article.

Of course,You can specify what to package by configuring the Files field.

For example, if we only package the SRC folder, index.js, and package.json, we can configure it like this:

"build": {
  "files": [
    "package.json",
    "index.js",
    "src/**/*"
  ]
}
Copy the code

Automatic updates

To automatically update, the installation of the application package should be stored in the Internet on a server, every time to open the application, automatic detection, based on the current application version and the online version of the match, when found there is a new version automatically download, after the download is complete, asks the user whether to install the new version.

Package different versions

In package.json, there is a “version” field that determines the current version.

  • Step1: set"Version" : "1.0.0"Run,npm run pack
  • Step2: set"Version" : "" 1.0.1Run,npm run pack

Although we did not change the content of the application, it will be recognized as “1.0.0” and “1.0.1” versions.

Set up a server to put the installation package

We start a server locally and put the latest version of the installation package resources.

  • 1. Initialization
mkdir tasky-server
cd tasky-server
npm init -y
npm install koa koa-static --save
Copy the code
  • 2. Create one in tasky-serverindex.js, the contents are as follows:
const Koa = require('koa')
const app = new Koa()

const static = require('koa-static')
const path = require('path')

app.use(static(path.join(__dirname,'./static')));

app.listen(9005)
Copy the code
  • 3, create astaticFolder to put the latest version of the installation package set. What files are included? Suppose the latest version is “1.0.1”.

Mac platform: Latest mac.yml, tasky-1.0.1-mac. zip, tasky-1.0.1.dmg, tasky-1.0.1.dmg. Blockmap

Windows: Latest. Yml, Tasky 1.0.1.msi, Tasky Setup 1.0.1.exe, Tasky Setup 1.0.1.exe. blockMap

  • 4. Start the server.node index.js

Detection of update

Detection updates can be achieved with the aid of the electron updater. Combined with the electron- Builder, it is very simple to implement. Go straight to the code.

  • First, configure in build"publish"Fields:
"build": {
    ...
    "publish": [
      {
         "provider": "generic",
         "url": "http://127.0.0.1:9005/" 
      }
    ]
}
Copy the code

Step 2: Call the electron- Updater module in the main process of the application to detect the update.

const { autoUpdater } = require('electron-updater') function checkUpdate(){ if(process.platform == 'darwin'){ / / we will use the koa - static static set directory into the static folder, / / so visit http://127.0.0.1:9005/darwin, is equivalent to access static/Darwin folder, Win32 similarly autoUpdater. SetFeedURL (' http://127.0.0.1:9005/darwin ') / / set to update to check path} else { AutoUpdater. SetFeedURL (' http://127.0.0.1:9005/win32 ')} / / testing update autoUpdater checkForUpdates () / / monitor 'error' event AutoUpdater. On ('error', (err) => {console.log(err)}) // Listen for 'update-available' events, Autoupdater. on('update-available', () => {console.log('found new version')}) // The new version is automatically downloaded by default. Set autoUpdater. AutoDownload = false // Listen to the 'update-Downloaded' event, On ('update- Downloaded ', () => {dialog.showMessageBox({type: 'info', title: 'App Update ', message: 'New version found, update? ', buttons: [' yes ', 'no ']}).then(buttonIndex) => {if(buttonIndex.response == 0) { Install the new version autoUpdater. QuitAndInstall () app. The quit ()}})})} app. On (' ready '() = > {/ / every time start the program, check the update checkUpdate ()}Copy the code

What is the basis for deciding whether to update?

The electron-updater will be in the path specified by the setFeedURL abovelatest.ymlIn theversionTo determine whether an update is needed that is larger than the current versionversionYou need to update, otherwise do not update..ymlIt’s also a configuration file, something like the one we use.jsonConfiguration file, which is written differently.

Github based solution

If you don’t want to build your own server, you can also use Github. Use Github to publish automatically instead of manually uploading the latest installation resources each time.

Automatic release

The first step, again, is to configure the “Publish” field.

"build": {
    ...
    "publish": ['github']
}
Copy the code

Step 2: Configure the new directive in “scripts”, which requires GH_TOKEN due to Github permission control, at github.com/settings/to… GH_TOKEN is generated in.

"scripts": { ... "release": "cross-env GH_TOKEN=ghp_KmVD3....... W2k3Pd4vV electron-builder" }Copy the code

The third step is NPM run release, which will package the resources and upload them to Github to generate a release Draft. You can find the draft in the Github project and publish release.

Detection of update

Similar to the above, for Windows, the code is as follows.

Const {autoUpdater} = the require (' electron - updater) function checkUpdate () {/ / testing update autoUpdater. CheckForUpdates () AutoUpdater. On ('error', (err) => {console.log(err)}) // Listen for 'update-available' events, Autoupdater. on('update-available', () => {console.log('found new version')}) // The new version is automatically downloaded by default. Set autoUpdater. AutoDownload = false // Listen to the 'update-Downloaded' event, On ('update- Downloaded ', () => {dialog.showMessageBox({type: 'info', title: 'App Update ', message: 'New version found, update? ', buttons: [' yes ', 'no ']}).then(buttonIndex) => {if(buttonIndex.response == 0) { Install the new version autoUpdater. QuitAndInstall () app. The quit ()}})})} app. On (' ready '() = > {/ / every time start the program, check the update checkUpdate ()}Copy the code

conclusion

In our example above, the web resources of the page are packaged into the installation package. In another case, the Web resources are separated from the “app shell”. The Web resources are placed on the server and dynamically loaded over the network each time, as follows:

mainWindow.loadURL('https://juejin.cn')
Copy the code

In the case of frequent business updates, you can use this method to achieve quick and barrier-free updates. In this case, we can package and update the “shell”, that is, the main process, as described above; The packaging of page resources is the same as the packaging of ordinary front-end projects, which will not be described here.

This article focused on packaging applications and automatic updates using the Electron Builder. In the next article, we’ll look at the combination of electron and Vue.

Thank you for reading, if you think it is good, welcome to like oh ❤️❤️!

For more technical exchanges, please follow my official account: Alasolala