转自:https://www.hangge.com/blog/cache/detail_2667.html
一、环境搭建教程1:在原有 Vue 项目上添加 Electron
1,Electron 介绍
(1)Electron 是由 Github 开发,用 HTML、CSS 和 JavaScript 来构建跨平台桌面应用程序的一个开源库。
- Electron 通过将 Chromium 和 Node.js 合并到同一个运行时环境中,并将其打包为 Mac、Windows 和 Linux 系统下的应用来实现这一目的。
- 简单来说,Electron 相当于一个浏览器的外壳,可以把网页程序嵌入到壳里面,这样就可以把网页打包成一个在桌面运行的程序。
(2)官网地址:https://electronjs.org/
2,搭建 Vue 开发环境
(1)Vue.js 作为目前最热门的前端开发框架,本文演示如何搭建一个 Vue + Electron 开发环境。首先是搭建 Vue 开发环境,这里使用脚手架工具 vue-cli,具体步骤参考我之前写的文章:
(2)Vue 项目创建完毕后,执行 npm run dev 命令可以启动项目,使用浏览器能够访问到如下页面即表示构建成功:
(3)然后执行 npm run build 命令可对项目进行打包,打包完成后,项目中会生成 dist 文件夹。
3,安装 Electron 依赖包
(1)由于网络问题,使用 npm 安装 Electron 会比较慢,甚至完全没有进度(一直卡在 postinstall)。这里我改用 cnpm,首先执行如下命令安装 cnpm:
1 |
|
(2)安装后执行 cnpm -v 查看是否安装成功:
(3)接着进入 Vue 项目文件夹执行如下命令安装 Electron 依赖:
1 |
|
(4)接着还需要执行如下命令安装 electron-builder,这个是用来将项目打包成可执行程序以及安装包:
1 |
|
(5)安装后查看项目的 package.json 文件,可以看到这个两个依赖都已添加:
4,配置 Vue 项目
(1)首先在 Vue 项目根目录下创建一个 main.js 文件,它是 Electron 主程序入口,具体内容如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
|
(2)接着编辑 Vue 项目的 package.json 文件,添加如下高亮内容:
- 第 7 行:指明主文件入口(即上面添加的 main.js 文件)
- 第 8~21 行:打包成可执行程序以及安装包的相关配置,注意里面 files 节点配置了哪些文件需要打包到应用中,主要是 dist 文件夹下内容以及项目根目录下的 main.js(如果没这个配置会造成打开应用是显示空白的问题。)
- 第 29~31 行:在原来 vue 相关命令的基础上,增加了electron 程序运行、打包命令。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
|
5,运行桌面应用
(1)在项目文件夹下依次执行如下命令,进行编译并运行:
1 2 |
|
(2)可以看到我们的桌面应用运行起来了:
6,生成可执行程序
(1)在项目文件夹下依次执行如下命令,进行编译并打包:
1 2 |
|
(2)由于我使用的是 macOS 系统,那么打包完毕后就会在项目 dist/mac 文件夹下就会生成可执行程序,双击即可执行(如果是 windows 系统则会生成 exe 程序):
7,生成安装包
(1)在项目文件夹下依次执行如下命令,进行编译并打包:
1 2 |
|
(2)命令执行完毕后除了跟上面一样会生成可执行程序外,还会生成一个安装文件(macOS 系统是 dmg,windows 系统是 exe)
(3)双击它即可进行安装: