preface

This article describes a way to migrate an existing VUE single-page project to ELECTRON using vuE-CLI-plugin-electron-Builder.

The following will take the famous Vue Element Admin as an example to detail how to make it a two-ended project.

The selection

When it comes to transferring Vue to Electron, many materials on the Internet introduce how to use Electron Vue, but after comparison and practice, I choose Builder for the following reasons:

  1. Builder updates are maintained in a more timely manner and have fewer issues, compared to the electron vue update which basically stagnates and has more problems

  1. The electron version used by electric-Vue was older, while the Electron version used by Builder kept up with the official pace
  • Electron – Vue uses 2.0.4 electron:

  • The Electron version of Builder is now 11.2.1:

  1. Electron vue is a set of project templates based on VUE-CLI2, while Builder is a scaffolding plug-in based on Vue-CLI3

Project practice also proves that this is a wise choice

Migration steps

Get into the business

The first step is to find your Vue project. This article uses Vue Element Admin as an example. OK, let’s download this project first:

git clone https://github.com/PanJiaChen/vue-element-admin.git
Copy the code

Step 2, install dependencies:

cd vue-element-admin
npm i
Copy the code

Run and see:

npm run dev
Copy the code

After the first two steps, we have a great Vue project:

Step 3, install the dependencies required for the ELECTRON project:

Not much, just 4 basic ones:

NPM i-d electron@^9.0.0 NPM i-d electron- devtools-Installer @^3.1.0 NPM i-d electron-icon-builder@^2.0.1 NPM i-d Vue cli - plugin - electron - builder @ ~ 2.0.0 - rc. 5Copy the code

There are two types of problems you may encounter when installing dependencies:

  1. The electron installation is very slow, and it doesn’t even fit
  2. A certificate error

The first type of problem can be solved by setting up mirroring:

npm config set registry https://registry.npm.taobao.org/
npm set electron_mirror https://npm.taobao.org/mirrors/electron/
npm set ELECTRON_MIRROR https://cdn.npm.taobao.org/dist/electron/
Copy the code

Certificate errors occur during company installation and are related to the agent used by the company. You can solve the problem as follows:

npm config set strict-ssl false// Notice that you change HTTPS to HTTP: NPM configset registry http://registry.npm.taobao.org/
npm set electron_mirror http://npm.taobao.org/mirrors/electron/
npm set ELECTRON_MIRROR http://cdn.npm.taobao.org/dist/electron/
Copy the code

Step 4: Separate the main process from the renderer process

If you use vue-cli-plugin-electric-Builder to create your project, it defaults to background-js for the main process and places it in the SRC directory with the renderer’s files.

I still prefer the electron Webpack approach: separate two directories under SRC: main and renderer. Main puts the main process-specific code, and renderer puts the renderer-specific code. Electron vue does the same thing.

OK, we also split two directories under SRC: main and renderer, and then put all the modules under SRC into the renderer.

Create index.js in main (main process code) and fill in the following code:

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: {
      <% if (spectronSupport) { %>
      // Required for Spectron testing
      enableRemoteModule: true}, < % % >// 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
    }
  })

  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

Step 5: Configure vue.config.js:

Note pluginOptions. ElectronBuilder. The config mainProcessFile and configureWebpack. Entry. App, configuration details visible: builder and cli, to pay special attention to the processing of SVG.

module.exports = {
  pluginOptions: {
    electronBuilder: {
      mainProcessFile: 'src/main/index.js'.builderOptions: {
        appId: "catpoint.com".productName: "Catpoint".icon: "./public/icons/icon.ico".files: ["* * / *"."static/*"].asar: true.mac: {
          icon: "./public/icon.png".target: ["zip"."dmg"].category: "com.catpoint-category.utilities"
        },
        win: {
          icon: "./public/icons/icon.ico".target: ["zip"."nsis"]},nsis: {
          oneClick: false.allowElevation: true.allowToChangeInstallationDirectory: true.installerIcon: "./public/icons/icon.ico".uninstallerIcon: "./public/icons/icon.ico".installerHeaderIcon: "./public/icons/icon.ico".createDesktopShortcut: true.createStartMenuShortcut: true.license: "./LICENSE.txt"}}}},...configureWebpack: config= > {
    config.entry.app = './src/renderer/main.js'
    return {
      name: name,
      resolve: {
        alias: {
          The '@': resolve('src/renderer'}}}}...chainWebpack(config) {
    config.module
      .rule('svg')
      .exclude.add(resolve('src/renderer/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/renderer/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
     .end()
  }
}
Copy the code

Step 6: Configure the script command:

"scripts": {
    "dev:desktop": "npm run copy && vue-cli-service electron:serve --mode dev"."dev:web": "vue-cli-service serve"."build:desktop": "npm run build:icon && npm run build:mac && npm run build:win"."build:win": "vue-cli-service electron:build --legacy --windows --x64"."build:mac": "vue-cli-service electron:build --legacy --macos"."build:icon": "electron-icon-builder --input=./public/icon.png --output=public --flatten"."build:web": "vue-cli-service build". },Copy the code

Well, this is the end of the migration, with support for dual-end debugging and packaging, and if things go well, half an hour. Run NPM run dev:desktop and NPM run dev:web to see the results.

You can also check this out: Proton Admin, a transformation of the Electron project based on the Vue Element Admin, under continuous improvement and enhancement.