从0开始搭建
概要
将html打包成桌面的主流有electron和nwjs,nwjs更加简单,但是使用效果不如electron,electron打包比较麻烦,但是效果比较好,反正各有优势和缺点
步骤
基础软件
shell
# 验证版本
node -v
v22.13.0
- npm
nodejs自带npm,直接查看版本
shell
npm -v
10.9.2
- cnpm
国内用户需安装这个,你懂的
shell
#使用 npm 全局安装 cnpm
npm install -g cnpm --registry=https://registry.npm.taobao.org
- 生成项目
- 创建目录 my-electron-app
- 进入目录,命令创建
shell
cnpm init -y
# -y 参数表示使用默认配置快速初始化,免去手动回答一系列问题的步骤。
- 添加依赖
shell
# 用于开发
cnpm install electron --save-dev
# 用于打包
cnpm install electron-builder --save-dev
- 指定国内地址
打包时会到github下载很多文件,如果连接github不顺畅,可以指定国内地址
js
"build": {
"electronDownload": {
"mirror": "https://registry.npmmirror.com/-/binary/electron/"
},
"appId": "com.cn.app",
"mac": {
"target": "dmg"
},
"win": {
"target": "nsis"
},
"linux": {
"target": "AppImage"
}
},
- 完整项目结构
- app:需要打包的html网站,这里测试添加了一个简单的html单文件
- dist:打包后文件目录
- node_modules:node依赖包,自动生成的
- main.js:项目主入口,package.json中指定
- package.json:项目结构
main.js
js
const { app, BrowserWindow } = require('electron');
const path = require('path');
function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
});
// win.loadURL('https://github.com');
win.loadFile(path.join(__dirname, 'app', 'index.html'));
}
app.whenReady().then(createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
package.json
js
{
"name": "my-electron-app",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "electron .",
"build": "electron-builder"
},
"build": {
"electronDownload": {
"mirror": "https://registry.npmmirror.com/-/binary/electron/"
},
"appId": "com.cn.app",
"mac": {
"target": "dmg"
},
"win": {
"target": "nsis"
},
"linux": {
"target": "AppImage"
}
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"electron": "^34.2.0",
"electron-builder": "^25.1.8"
}
}
运行项目
js
# cmd命令
cnpm run start
运行后出现浏览器,里面是app包含的网站
打包项目
js
cnpm run build
- 打包中会出现访问winCodeSign(github)失败,这个主要用于软件签名,防止软件被篡改,如果签名失败也会打包项目,但是项目名字是
win-unpacked
,意思未签名打包目录 - 打开win-unpacked
注意事项
- 远程打包失败,可以下载electron到本地,指定本地打包
https://npmmirror.com/mirrors/electron/
更多方法豆包[electron国内下载打包方法]