Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money

A brief introduction.

After completing the development of the dynamic module hot reload feature, it’s time to take a look at the final step — packaging.

Source: github.com/Kuari/Blog/…

Series of articles:

  • Vite+Electron quickly build a VUE3 desktop application
  • Vite+Electron quickly build a VUE3 desktop application (ii) — dynamic module thermal overload
  • Vite+Electron quickly build a VUE3 desktop application (iii) — pack

2. Train of thought

The main point is mainWindow.loadurl ().

It will not work if http://localhost:3000 is loaded after packing. Therefore, you need to pack it with Vite first and then use the electron Builder to load the vite packed file for packing.

In order for the code to be able to load http://localhost:3000 at run time and the file at package time depending on the environment, you need to use environment variables to switch between production and development environments.

3. Implement

1. Environment variables

The environment variable NODE_ENV is used here to switch between production and development environments. The production environment is NODE_ENV=production, and the development environment is NODE_ENV=development. If there are other environments such as release, you can expand on this basis.

2. Create the electron folder

Create the folder electron under the project root and move the main.js and preload.js files in. Its structure is as follows:

. ├ ─ ─ the README. Md ├ ─ ─ electron │ ├ ─ ─ the main, js │ └ ─ ─ preload. Js...Copy the code

If still not quite understand can look at the source file structure.

3. Edit the electron/main. Js

This file mainly needs to switch the content of the electron loading according to the environment variables. The modification is as follows:

mainWindow.loadURL(
  NODE_ENV === 'development'
  ? 'http://localhost:3000'
  :`file://${path.join(__dirname, '.. /dist/index.html')}`
);
Copy the code

The revised contents are as follows:

// electron/main.js

// Controls the application lifecycle and creates modules for native browser Windows
const { app, BrowserWindow } = require('electron')
const path = require('path')

const NODE_ENV = process.env.NODE_ENV

function createWindow () {
  // Create a browser window
  const mainWindow = new BrowserWindow({
    width: 800.height: 600.webPreferences: {
      preload: path.join(__dirname, 'preload.js')}})/ / load index. HTML
  // mainwindow.loadfile ('dist/index.html') change this line to the following line to load the URL
  mainWindow.loadURL(
    NODE_ENV === 'development'
      ? 'http://localhost:3000'
      :`file://${path.join(__dirname, '.. /dist/index.html')}`
  );

  // Open the development tool
  if (NODE_ENV === "development") {
    mainWindow.webContents.openDevTools()
  }

}

// This program will be initialized at Electron
// when creating a browser window
// Parts of the API can only be used after the ready event is triggered.
app.whenReady().then(() = > {
  createWindow()

  app.on('activate'.function () {
    // Usually on macOS, when clicking the app icon in the Dock, if nothing else
    // Open the window, then the program will create a new window.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

Exit the program when all Windows are closed except macOS. Therefore, it is common for programs and they are in
For ICONS on the taskbar, they should remain active until the user exits using Cmd + Q.
app.on('window-all-closed'.function () {
  if(process.platform ! = ='darwin') app.quit()
})

// In this file, you can include the rest of the application code,
// It can also be split into several files and imported with require.
Copy the code

4. Edit package. Json

First, change the main property to main: main.js and change it to main: electron/main.js.

{
  "name": "kuari"."version": "0.0.0"."main": "electron/main.js". }Copy the code

Next, edit the Build property:

"build": {
  "appId": "com.your-website.your-app"."productName": "ElectronApp"."copyright": "Copyright © 2021 < your name >"."mac": {
    "category": "public.app-category.utilities"
  },
  "nsis": {
    "oneClick": false."allowToChangeInstallationDirectory": true
  },
  "files": [
    "dist/**/*"."electron/**/*"]."directories": {
    "buildResources": "assets"."output": "dist_electron"}}Copy the code

Then, update the scripts property.

Two libraries need to be installed:

  • Cross-env: This library lets developers focus on setting environment variables without worrying about platform Settings
  • Electron – Builder: electron packing library
yarn add -D cross-env electron-builder
Copy the code

The updated scripts look like this:

{
  "dev": "vite"."build": "vite build"."serve": "vite preview"."electron": "wait-on tcp:3000 && cross-env NODE_ENV=development electron .".// Environment variables need to be set here to ensure that the URL is loaded at development time
  "electron:serve": "concurrently -k \"yarn dev\" \"yarn electron\""."electron:build": "vite build && electron-builder" // Add the package command
}
Copy the code

Finally, the complete contents of the updated package.json are as follows:

{
  "name": "kuari"."version": "0.0.0"."main": "electron/main.js"."scripts": {
    "dev": "vite"."build": "vite build"."serve": "vite preview"."electron": "wait-on tcp:3000 && cross-env NODE_ENV=development electron ."."electron:serve": "concurrently -k \"yarn dev\" \"yarn electron\""."electron:build": "vite build && electron-builder"
  },
  "dependencies": {
    "vue": "^ 3.2.16"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^ 1.9.3." "."concurrently": "^ 6.3.0"."cross-env": "^ 7.0.3." "."electron": "^ 15.1.2." "."electron-builder": "^ 22.13.1"."vite": "^" 2.6.4. ""."wait-on": "^ 6.0.0"
  },
  "build": {
    "appId": "com.my-website.my-app"."productName": "MyApp"."copyright": "Copyright © 2021 kuari"."mac": {
      "category": "public.app-category.utilities"
    },
    "nsis": {
      "oneClick": false."allowToChangeInstallationDirectory": true
    },
    "files": [
      "dist/**/*"."electron/**/*"]."directories": {
      "buildResources": "assets"."output": "dist_electron"}}}Copy the code

4. Packaging

Run the package command to start the package.

yarn electron:build
Copy the code

After the packing is complete, there will be two more folders dist and dist_electron, which have the following file structure:

. ├ ─ ─ the README. Md ├ ─ ─ dist │ ├ ─ ─ assets │ ├ ─ ─ the favicon. Ico │ └ ─ ─ index. The HTML ├ ─ ─ dist_electron │ ├ ─ ─ MyApp - 0.0.0 - MAC. Zip │ ├ ─ ─ MyApp - 0.0.0 - MAC. Zip. Blockmap │ ├ ─ ─ MyApp - 0.0.0. DMG │ ├ ─ ─ MyApp - 0.0.0. DMG. Blockmap │ ├ ─ ─ builder - debug. Yml │ ├ ─ ─ Builder - effective - config. Yaml │ └ ─ ─ MAC...Copy the code

At this point, the packaging is complete.

Later, I will write about the optimization of electron to reduce the volume applied after electron packing. (This thing is a bit big to pack/dog head)

5. Original blog

  • Vite+Electron quickly build a VUE3 desktop application (iii) — pack