Introduce electron into the original vue (react) project and package it into a desktop application (the latest on the entire network!)

Based on the original project using electron to package into a desktop application

First understand what electron is?

Software Introduction

Electron is a cross-platform desktop application built using JavaScript, HTML, and CSS. It is based on Node.js and Chromium and is used by the Atom editor and many other applications.

Electron is compatible with Mac, Windows, and Linux, allowing you to build applications for all three platforms.

Enter topic:

  1. Add electron package to vue (install globally using npm naming)
 npm install electron -g
  1. Vue project adds Electron-builder packaging tool
 vue add electron-builder

Note: If the electron installation fails, or if the package download from github fails when using electron-builder for packaging later, please set up the electron image.

Set up mirroring method:

npm config edit

Explanation: Using this command will pop up the npm configuration document, copy the following content to the end of the file.

electron_mirror=https://npm.taobao.org/mirrors/electron/
electron-builder-binaries_mirror=https://npm.taobao.org/mirrors/electron-builder-binaries/

  1. Add background.js to the project root directory (you can name it yourself), and then write the following code:
"use strict";

import {<!-- --> app, protocol, BrowserWindow, Menu } from "electron";
import {<!-- --> createProtocol } from "vue-cli-plugin-electron-builder/lib";
import installExtension, {<!-- --> VUEJS_DEVTOOLS } from "electron-devtools-installer";
const isDevelopment = 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: 1260,
    height: 800,
    // frame: false, // If you need to remove the window border
    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, // Use Node.js module in wizard page
      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");
  }
}

//Hide client default menu
Menu.setApplicationMenu(null);

// 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 & amp; & amp; !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();
    });
  }
}

  1. Add it to the package.json file
"main": "background.js",

Run the test:

npm run serve--web page
npm run electron:serve--client

Project packaging:

npm run electron:build

Note: If you package, an error will be reported! ! !
You may encounter Error when using Node.js v19.x.x version: error:0308010C:digital envelope routines::unsupported
Reason: The OpenSSL version used is not supported.

Solution:
Check your node version and try to use the v16 version! !

Other possible solutions to problems:

Open the node_module/app-builder-lib/out/targets/nsis/NsisTarget.js file and add the parameters we need in the executeMakensis method

{<!-- -->
args.push("-INPUTCHARSET", "UTF8");
}

Additional 1 Replace the client icon and configure the installer

Enter the project path and check whether a file with the same name as vue.config.js exists (it seems that vue3 does not have it, but vue2 does). If not, create an empty file. Add the following code:

module.exports = {<!-- -->
  pluginOptions: {<!-- -->
      electronBuilder: {<!-- -->

          customFileProtocol: "/", //Solve the element icon problem (cause: due to packaging, the element-ui style is not referenced as a static resource)

          builderOptions: {<!-- -->
            "appId": "com.tomatoLRX.app",
            "productName": "SPTSystem",//The project name is also the name of the generated installation file, that is, aDemo.exe
            "copyright": "Copyright ? 2023",//Copyright information
            "directories": {<!-- -->
              "output": "./dist"//Output file path, the default compiled before is dist_electron
            },
           win: {<!-- -->
              icon: "vueApp.ico", //Pay attention to the icon path here
              target: [
                 {<!-- -->
                   target: "nsis", //Use nsis to create an installation program, the suffix of the package file is exe
                   arch: [
                   "x64", //64 bit
                   "ia32", //32 bit
                   ],
                 },
             ], //Add a custom installation wizard
          },
        nsis: {<!-- -->
             oneClick: false, //Create a one-click installer or a secondary installer
             language: "2052", //Installation language
             perMachine: true, //Apply to all users
             allowToChangeInstallationDirectory: true, //Users can choose the path
            },
            // options placed here will be merged with default configuration and passed to electron-builder
          }
      }
  }
}

For more configuration, please refer to the configuration of electron-builder:

"build": {<!-- -->
    "productName":"xxxx", //Project name This is also the prefix name of the generated exe file
    "appId": "com.xxx.xxxxx", //Package name
    "copyright":"xxxx", //Copyright information
    "directories": {<!-- --> //Output folder
      "output": "build"
    },
    "nsis": {<!-- --> //nsis related configuration, effective when the packaging method is nsis
      "oneClick": false, // Whether to install with one click
      "allowElevation": true, // Allow request for elevation, if false, the user must restart the installer with elevated privileges.
      "allowToChangeInstallationDirectory": true, // Allow modification of the installation directory
      "installerIcon": "./build/icons/aaa.ico", // Installation icon
      "uninstallerIcon": "./build/icons/bbb.ico", //Uninstall icon
      "installerHeaderIcon": "./build/icons/aaa.ico", // Head icon during installation
      "createDesktopShortcut": true, // Create desktop icon
      "createStartMenuShortcut": true, // Create start menu icon
      "shortcutName": "xxxx", // Icon name
      "include": "build/script/installer.nsh", // Included custom nsis script
    },
    "publish": [
      {<!-- -->
        "provider": "generic", // Server provider, it can also be GitHub, etc.
        "url": "http://xxxxx/" // Server address
      }
    ],
    "win": {<!-- -->
      "icon": "build/icons/aims.ico",
      "target": [
        {<!-- -->
          "target": "nsis", //Use nsis to create an installation package, and "portable" package it into an installation-free version.
          "arch": [
            "ia32", //32 bit
            "x64" //64 bit
          ]
        }
      ]
    },
    "mac": {<!-- -->
      "icon": "build/icons/icon.icns"
    },
    "linux": {<!-- -->
      "icon": "build/icons"
    }
  }

Additional 2 Hide client default menu

The main of the program is background.js, find it and open it for editing

Inside is the electron code, modify it directly, add a Menu reference, and then set the program menu to null. When you run it, you will find that the menu is gone, and you can repackage it.

import {<!-- --> Menu } from "electron";
//Hide client default menu
Menu.setApplicationMenu(null);