preface

This paper builds scaffolding based on vuE-cli-plugin-electron – Builder provided by Vue CLI. If you’re a front-end developer who wants to convert existing pages to desktop software and can run Windows, MAC, and Linux versions, Electron is a good choice.

Preparation before development

At the end of the day, Electron is essentially a Chromium-based application, and in plain English, the desktop software is a browser, and what we write is displayed in the browser, and you have to know the front troika of HTML, CSS and JavaScript before you can develop it, With a little node knowledge when it comes to special processing such as files, Electron can call node directly, which a browser can’t do.

The installation

NPM install --registry= HTTPS://registry.npm.taobao.orgThis command will open the configuration file for NPM. Please add registry= HTTPS in the blank space.//registry.npm.taobao.org/
electron_mirror=https://cdn.npm.taobao.org/dist/electron/ 
ELECTRON_BUILDER_BINARIES_MIRROR=http://npm.taobao.org/mirrors/electron-builder-binaries/# install vue-cli NPM install -g@vue /cli # create vue project vue create electron-vue CD electron-vue vue add electron- Builder # select the electron version number` 11.0.0 `There will be when the installation is complete`src/background.js`File,`package.json`NPM run electron: Serve # Wait a moment, a desktop window will appear, ok the installation is complete, let's change it.Copy the code

instructions

A note before the transformation: Electron development is different from our normal development in that it has two processes: the main process and the render process

  • Main process SRC/backback. js: Manages all rendering processes (how to configure desktop software, how to open desktop software, how to communicate with each other, etc.).
  • Render process: webpage in plain English (opening our single page webpage)

NPM run electron: What do serve do, in fact, is similar to run NPM run serve to start a web page port and generate a real-time package JS, then through the electron command to specify the js to start, using the main process to load the web page port. In layman’s terms, you can think of our desktop software as a browser, and the main process is to set the browser’s style (ICONS, sizes, etc.), and the render process is the page the browser opens.

transform

SRC directory modification

SRC/background-js SRC /main SRC /renderer SRC /main SRC /renderer SRC /main SRC/background-js SRC /main SRC /renderer SRC /main SRC /renderer Other files under SRC go into SRC /renderer. The current structure is as follows:

├─ SRC # source directory │ ├─ ├─ class # ├─ class # ├─ class # ├─ class # ├─ class # ├─ class # ├─ class # ├─ class # ├─ class # ├─ class # ├─ class # ├─ class # ├─ class # ├─ class # ├─ class # ├─ class # ├─ class # ├─ class # ├─ class # ├ ─main.js # import to the rendering processCopy the code

Add the vue. Config. Js

Since we changed the default entry file location, we should configure the corresponding parameters, create vue.config.js in the root directory, add

module.exports = {
  pluginOptions: {
    electronBuilder: {
      mainProcessFile: 'src/main/index.js'.// Main process entry file
      rendererProcessFile: 'src/renderer/main.js'.// Render process entry file
      mainProcessWatch: ['src/main'].If the main process file changes, the main process will be recompiled and restarted}}}Copy the code

Then restart NPM Run electron:serve to see if you can reboot.

Add: this configuration is fine if you pack only the single-page electron, but if you want to pack the NPM run build for the Web page, you will have a problem because we changed the entry file location.

Here we can modify its entry file by setting Pages, and this can also package multiple pages

module.exports = {
   pages: {
    index: {
      entry: 'src/renderer/main.js'.template: 'public/index.html'.filename: 'index.html'.title: 'electron-vue-cli'.chunks: ['chunk-vendors'.'chunk-common'.'index']},// loader: 'SRC /loader/main.js' // multi-page loader page
  },
  pluginOptions: {
    electronBuilder: {
      mainProcessFile: 'src/main/index.js'.// Main process entry file
      mainProcessWatch: ['src/main'].If the main process file changes, the main process will be recompiled and restarted}}}Copy the code

Note: RendererProcessFile (rendererProcessFile, rendererProcessFile, rendererProcessFile, rendererProcessFile, rendererProcessFile, rendererProcessFile, rendererProcessFile, rendererProcessFile, rendererProcessFile) Check whether it can run successfully (packaging may fail to download the electron package due to network reasons, please refer to the steps before installation to set up taobao source and set up the electron ontology download).

Environment Variable Configuration

Vue CLI can be read by using –mode xx. Env. xx Set environment variable reference, create in the root directory

Dev.env. Test # test.env. Prod # prod. NODE_ENV = development VUE_APP_ENV = development VUE_APP_APPID = com. Electron., electronVueDEV VUE_APP_PRODUCTNAME = electron development VUE_APP_VERSION=0.01.Env set NODE_ENV to development, and set production for othersNODE_ENV: VUE_APP_ENV: Env. Test is VUE_APP_ENV=test,.env.prod is VUE_APP_ENV=production VUE_APP_APPID: The appId electron configuration, com. Electron. ElectronVueDEV, com. Electron., electronVueTEST com. Electron., electronVue VUE_APP_PRODUCTNAME: Electron productName configuration, electron development, electron test, ·· VUE_APP_VERSION: electron version configurationCopy the code

Modify package.json scripts, remove original package command, add:

Web packaging:"build:dev": "vue-cli-service build --mode dev"."build:test": "vue-cli-service build --mode test"."build:prod": "vue-cli-service build --mode prod"The electron packing:"build:dev:win32": "vue-cli-service electron:build --mode dev --win --ia32"."build:dev:win64": "vue-cli-service electron:build --mode dev --win --x64"."build:test:win32": "vue-cli-service electron:build --mode test --win --ia32"."build:test:win64": "vue-cli-service electron:build --mode test --win --x64"."build:prod:win32": "vue-cli-service electron:build --mode prod --win --ia32"."build:prod:win64": "vue-cli-service electron:build --mode prod --win --x64"."build:dev:mac": "vue-cli-service electron:build --mode dev --mac"."build:test:mac": "vue-cli-service electron:build --mode test --mac"."build:prod:mac": "vue-cli-service electron:build --mode prod --mac".Copy the code

The electron packing is only configured for Win32, Win64, and MAC. If you have requirements for other modes, please refer to the link for self-configuration.

Environment variable detection and package configuration

Adding the Config Configuration

New the renderer/config/index. Js

const env = process.env

const config = {
  host: ' '.baseUrl: ' '
}

Object.assign(config, env)

// if (env.NODE_ENV === 'development') {
// config.VUE_APP_ENV = 'test'
// }

if (config.VUE_APP_ENV === 'development') {
  config.host = 'http://192.168.1.1:8080'
} else if (config.VUE_APP_ENV === 'test') {
  config.host = 'http://192.168.1.1:8080'
} else if (config.VUE_APP_ENV === 'production') {
  config.host = 'http://192.168.1.1:8080'
}

export default config

Copy the code

Local development switch environment, can be modified using the method commented above, or can be directly modified. Env file VUE_APP_ENV.

Packaging configuration

SRC /renderer/ app. vue add import CFG from ‘@/config’, print CFG

Vue. Config. Js added

const path = require('path')

function resolve(dir) {
  return path.join(__dirname, dir)
}

module.exports = {
  chainWebpack: (config) = > { // Since we changed the renderer directory, change the alias of '@'
    config.resolve.alias.set(The '@', resolve('src/renderer'))},builderOptions: {
    appId: process.env.VUE_APP_APPID,
    productName: process.env.VUE_APP_PRODUCTNAME,
    extraMetadata: {
      name: process.env.VUE_APP_APPID.split('. ').pop(),
      version: process.env.VUE_APP_VERSION
    },
    asar: true.directories: {
      output: "dist_electron".buildResources: "build".app: "dist_electron/bundled"
    },
    files: [{filter: [
          "* *"]}],extends: null.electronVersion: "11.3.0".extraResources: [].electronDownload: {
      mirror: "https://npm.taobao.org/mirrors/electron/"
    },
    dmg: {
      contents: [{type: "link".path: "/Applications".x: 410.y: 150
        },
        {
          type: "file".x: 130.y: 150}},mac: {
      icon: "public/icons/icon.icns"
    },
    nsis: {
      oneClick: false.perMachine: true.allowToChangeInstallationDirectory: true.warningsAsErrors: false.allowElevation: false.createDesktopShortcut: true.createStartMenuShortcut: true
    },
    win: {
      target: "nsis".icon: "public/icons/icon.ico".requestedExecutionLevel: "highestAvailable"
    },
    linux: {
      "icon": "public/icons"
    },
    publish: {
      provider: "generic".url: "http://127.0.0.1"}}... }Copy the code

BuilderOptions is the packaging configuration of Electron. Please refer to the link. Before packaging, downloading the electron package may fail or be very slow due to network reasons. Originally, the name and version values in electron are read from package.json. Here, extraMetadata is used to inject these two values into package.json.

icons

I need ICONS for packaging, I need Windows, I need ICO, I need ICNS for MAC, you can generate them using ICofX (I’ll add them later when I have time), but here I used a plugin to generate them directly

Yarn add -d electronic-icon-builder package.json add "ICONS ": "electron-icon-builder --input=./public/icons/icon.png --output=public --flatten",Copy the code

Create a new ICONS folder under public and put your icon.png(512*512) in it. Run NPM run ICONS to generate the corresponding images in them.

Finally: run the package command, respectively hit dev, test, prod package installation, open the software to check whether the printed CFG is correct.

supplement

If an error occurs using NPM install or YARN install, it may be a network problem. Delete node_modules and follow the installation steps to install NPM again

Gitee address: gitee.com/ldlw/electr…

Follow the author: wechat search [learn front] public account, that is, you can get the author’s wechat, plus technical exchange group