手把手教你 Electron + Vue 搭建前端桌面应用

7,865 阅读4分钟

一、在使用 Electron 之前我们要了解 Electron 是什么?

Electron 官网地址 点此 : electron 官方地址

Electron 相当于一个浏览器的外壳 , 我们将 编写的 HTML , CSS , Javascript 网页程序 嵌入进 Electron 里面

以便于在桌面上进行运行。 通俗来讲它就是一个软件 , 如 QQ 、网易云音乐、优酷视频 等等。功能至强大

超乎你的想象

二、开发环境的准备

  1. 安装 Node.js 坏境

    Node.js 官网地址 点此 node.js 官方地址

  2. 安装 Vue Cli

    npm install -g @vue/cli
    
  3. 安装 淘宝镜像 cnpm ( 因 electron 包 特别大 本人尝试过 npm 或 yarn 的 方法 需要等待很长时间 )

  4. 全局安装 Electron

    cnpm install electron -g
    
    //如果安装还是 特比慢 或 不想安装cnpn 可以联系我们
    

​ 查看 是否安装成功 :

elec2.jpg

三、 搭建 vue 环境

1. 首先使用 vue-cli 搭建基础 vue框架

elec3.png

和平时写 vue项目一样 选择自己需要的

elec4.jpg

cd electron-demo 进入项目目录

yarn serve 启动项目

四、vue项目中添加 electron 模块

输入 vue add electron-builder 后 按下回车

elec5.jpg

安装过程中 此处我们选择 ^13.0.0 按下回车

elec6.jpg

因 electron 安装时间过长 导致安装失败

elec7.jpg

elec8.jpg

解决办法 直接使用 cnpm install 进行安装

elec9.jpg

安装 完成后 我们使用 npm run electron:serve 运行项目 依旧是报错的。请耐心往下看完

elec10.jpg

此处 我们需要打开项目的目录 找到 node_modules 下的 electron 。 删除 这个文件以后 重新使用 cnpm install

elec12.jpg

至此。 electron 应用 已经搭建完成。 我们使用 npm run electron:serve 进行启动项目 ( windows 与 imac 一样 )

elec13.jpg

已经完美运行成功 可以看到桌面已经弹出 electron-demo 应用

五、查看electron+vue 项目目录

相比于 基础 vue 项目 我们可以发现在目录中 多出一个 background.js 文件

elec14.jpg

此处可以 配置 electron 应用的一些设置。 如窗口大小 、 是否可以缩放、是否可以移动窗口等等

elec15.jpg

Background.js 文件

'use strict'

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: 1120,
    height: 1090,
    minHeight: 700,
    minWidth: 1000,
    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,
      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')
  }
}

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

注意:打开和 关闭 开发者工具 请点击。 操作栏 > view > Toggle Developer tools

我们可以在官网的文档里搜索一下。进行一些配置 ( 详细配置请查看官网配置 ) 链接已经放在文章开头啦

六、打包 electron 应用

打包应用 使用 npm run electron:build 进行打包 ( imac 系统 和 windows系统 一样使用这个 )

此处 以 iMac 为例 ( 下面会有 windows 解决方案 )

elec16.jpg

当我们看到。 Build complete ! 时 就说明 打包成功 可以查看 dist_electron / mac 里面就是打包好的应用 ( 苹果系统 )

windows 解决方案
  • 打包 windows 应用时 我们需要将 整个项目的源码 上传到 windows 电脑上
  • 上传到 windows 电脑上后 同样需要安装 cnpm 不然 electron 是安装不上的
  • 打开项目目录 删除掉 node_modules 重新 cnpm install
  • 如果还是无法打包 删除掉 node_modules / electron 目录 重新 cnpm install
  • 然后运行 npm run electron:build 进行打包



PS:大家看了后觉得对自己有帮助可以三连留言,欢迎提出宝贵意见,也欢迎各位对相关技术有兴趣的开发者(由团队开发人员微信号x118422邀请)入群,在线解答讨论数据可视化、优化图表性能等方面的技术问题~