前言

本文介绍一种应用vue-cli-plugin-electron-builder(名字太长,以下简称builder),将现有的Vue单页我的项目迁徙到Electron的做法。

上面将会以驰名的Vue Element Admin为例,具体讲述如何把它变成一个双端我的项目

选型

说到Vue迁徙到Electron,网上许多材料都是介绍如何应用electron-vue,但通过比照与实际,我抉择应用builder,起因如下:

  1. builder的更新保护更及时,而且issues更少,相比之下,electron-vue的更新根本停滞了,问题也更多

  1. electron-vue应用的electron版本很旧,而builder应用的electron跟得上官网的步调
  • electron-vue用的是2.0.4的electron:

  • builder的electron版本当初是11.2.1:

  1. electron-vue是一套基于vue-cli2的我的项目模版,而builder是基于vue-cli3的脚手架插件

我的项目实际也证实这个抉择比拟理智^_^

迁徙步骤

进入正题

首先当然是找到你的Vue我的项目,本文以Vue Element Admin为例,OK,让咱们先下载这个我的项目:

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

第二步,装置依赖:

cd vue-element-adminnpm i

跑起来看看:

npm run dev

前两步走完,咱们就有了个棒棒的Vue我的项目:

第三步,装置electron我的项目所需的依赖:

不多,根本的就4个:

npm i -D electron@^9.0.0npm i -D electron-devtools-installer@^3.1.0npm i -D electron-icon-builder@^2.0.1npm i -D vue-cli-plugin-electron-builder@~2.0.0-rc.5

装置依赖的时候可能会遇到两类问题:

  1. electron装置非常迟缓,甚至装不上
  2. 证书谬误

第一类问题能够通过设置镜像来解决:

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/

证书谬误多见于在公司装置时产生,与公司应用的代理无关,能够通过如下办法解决:

npm config set strict-ssl false// 留神,把https都变成http:npm config set 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/

第四步,划分主过程与渲染过程

如果你应用vue-cli-plugin-electron-builder来创立我的项目,它默认是将主过程的源文件设置为background.js,与渲染过程的文件同放在src目录下。

我还是更喜爱electron-webpack的做法:在src下分出两个目录:main和renderer。main搁置主过程相干的代码,而renderer搁置渲染过程相干的代码。electron-vue也是这么做的。

OK,咱们也在src下分出两个目录:mainrenderer,而后将原来src下的模块都放进renderer中

在main中创立index.js(主过程代码),填入如下代码:

import { app, protocol, BrowserWindow } 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 readyprotocol.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()    })  }}

第五步,配置vue.config.js:

留神pluginOptions.electronBuilder.mainProcessFile和configureWebpack中的config.entry.app,配置的详情可见:builder和cli,还要特地留神对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: {          '@': 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()  }}

第六步,配置脚本命令:

"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",    ...},

好了,到这里就实现了迁徙,并且反对双端的调试和打包,顺利的话,半个小时就好了。运行npm run dev:desktop和npm run dev:web看看成果吧。

您也能够看看这个:Proton Admin,一个在Vue Element Admin根底上改建而来的Electron我的项目,在继续改良和加强中。