avatar

使用Electron将网页打包成桌面应用程序

准备好项目文件

编辑package.json,配置应用信息

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
{
"name": "electron-demo",
"version": "1.0.0",
"description": "Electron Demo",
"main": "index.js",
"scripts": {
"dev": "electron .",
"pack": "electron-packager ./ App --platform=win32 --arch=x64 --out ./dist --electron-version=8.2.3 --overwrite --icon=./src/icon.ico",
"dist": "electron-builder --win --ia32"
},
"build": {
"appId": "com.pengwf.app",
"electronVersion": "8.2.3",
"publish": [
{
"provider": "generic",
"url": "https://www.pengwf.com/"
}
],
"win": {
"target": "nsis",
"icon": "./src/icon.ico"
}
},
"keywords": [
"Electron"
],
"author": "pengweifu",
"license": "ISC",
"devDependencies": {
"electron": "^8.2.3",
"electron-builder": "^22.4.1",
"electron-packager": "^14.2.1"
}
}

其中

  1. main为脚本入口
  2. scripts.dev 为测试脚本
  3. scripts.pack 为打包可执行文件脚本
  4. scripts.dist 为打包安装文件脚本
  5. build为打包安装文件时的配置信息,其中icon为程序图标,在window10平台下格式应为*.ico,尺寸必须>=256px
  6. devDependencies需要添加electron+electron-builder+electron-packager依赖

编辑index.js

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
const { app, BrowserWindow } = require('electron')

function createWindow () {
// 创建浏览器窗口
let win = new BrowserWindow({
show: false,
resizable: false, // 禁止缩放
fullscreen: true, // 全屏
frame: false, // 无边框
autoHideMenuBar: true, // 隐藏菜单栏
webPreferences: {
nodeIntegration: true
}
})

// 加载src/index.html文件
win.loadFile('src/index.html')

win.once('ready-to-show', () => {
win.show()
})

win.on('closed', () => {
win = null
})
}

app.whenReady().then(createWindow)

安装依赖

国内通过npm默认镜像安装依赖特别慢,需要修改为淘宝的镜像

1
2
registry=https://registry.npm.taobao.org
ELECTRON_MIRROR=https://npm.taobao.org/mirrors/electron/

测试

可以通过执行npm run dev来进行测试

制作安装包

可以通过执行npm run dist来制作安装包,由于打包过程中需要从github下载文件,可能遭遇多次失败,试了好几次都失败了,还是翻墙吧.

文章作者: pengweifu
文章链接: https://www.pengwf.com/2020/04/22/other/TOOL-Electron/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 麦子的博客
打赏
  • 微信
    微信
  • 支付宝
    支付宝

评论