从Vue到Electron

前言

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

下面将会以著名的Vue Element Admin为例,详细讲述如何把它变成一个双端项目

选型

说到Vue迁移到Electron,网上许多资料都是介绍如何使用electron-vue,但经过对比与实践,我选择使用builder,原因如下:

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

从Vue到Electron_第1张图片

从Vue到Electron_第2张图片

  1. electron-vue使用的electron版本很旧,而builder使用的electron跟得上官方的步伐
  • electron-vue用的是2.0.4的electron:

从Vue到Electron_第3张图片

  • builder的electron版本现在是11.2.1:

从Vue到Electron_第4张图片

  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-admin
npm i

跑起来看看:

npm run dev

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

从Vue到Electron_第5张图片

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

不多,基本的就4个:

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.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 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()
    })
  }
}

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

注意pluginOptions.electronBuilder.mainProcessFile和configureWebpack中的config.entry.app,配置的详情可见:buildercli,还要特别注意对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项目,在持续改进和增强中。

你可能感兴趣的:(从Vue到Electron)