electron
Electron
: 使用 JavaScript(TypeScript)、HTML、CSS 构建跨平台(Windows、MacOs、Linux)的桌面应用开发框架。该框架基于 Chromium 与 Nodejs 实现,因此可无缝使用 web 前端的界面库进行桌面应用开发。

工程构建
安装 NodeJs
传统工程
Note
使用 cnpm 代替 npm 进行 electron 安装,npm 安装会卡住。
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
Hello World
</div>
</body>
</html>index.js
const { app, BrowserWindow } = require('electron')
const createWindow = () => {
// 创建主窗口
const win = new BrowserWindow({
width: 800,
height: 600
})
// 加载主界面
win.loadFile('index.html')
}
// 应用程序启动
app.whenReady().then(() => {
createWindow()
})package.json
{
"name": "electron",
"version": "1.0.0",
"main": "index.js", // 程序入口
"scripts": {
"start": "electron .", // 启动程序命令
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"devDependencies": {
"electron": "^35.2.1"
}
}

[!note|style:flat] 使用传统方案构建
electron构建应用程序特别繁琐,每一个界面都需要单独定义一个html界面,不推荐使用
vue3 工程
vue
是目前比较流行的一个 web 前端开发框架,相比于传统的纯手撸 html 脚本,基于 vue 进行界面开发更简便,且 vue 还拥有较多的 UI 组件库,对非前端开发人员来说使用更加友好。
[!warning|style:flat] 该方式构建项目,请先学习 vue3 ,且该笔记将只详细介绍 vue 工程的开发方式。
调试
debug
-
打开
package.json -
找到
scripts配置项 -
点击
debug script即可进入调试模式
开发工具
在浏览器中可以按 f12 打开 web 开发工具, electron 客户端程序中也可以启用该开发工具进行 UI 界面开发。
function createWindow(): void {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 900,
height: 670,
show: false,
autoHideMenuBar: true,
...(process.platform === 'linux' ? { icon } : {}),
webPreferences: {
preload: join(__dirname, '../preload/index.js'),
sandbox: false
}
})
// NOTE - 创建的窗口打开开发工具
mainWindow.webContents.openDevTools()
// ....
}Tip
默认使用 ctrl + shift + i 键可打开开发工具
打包
- 给
powershell挂梯子,代理软件可能无法自动给终端挂梯子
- 以 「管理员」 权限重启
powshell,打包程序可能会在c盘创建文件,因此必须给管理员权限 - 启动代理
- 执行打包
// package.json
{
"scripts": {
// ...
"build:unpack": "npm run build && electron-builder --dir",
"build:win": "npm run build && electron-builder --win",
"build:mac": "npm run build && electron-builder --mac",
"build:linux": "npm run build && electron-builder --linux"
// ...
}
}Note
出现打包异常,需要手动删除 C:\Users\主机名\AppData\Local 下的 electron 与 electron-builder 文件夹