本文主要是介绍Electron入门项目及打包,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Electron入门项目及打包
环境:
electron: v30.1.1 (2024-06-13)
nodejs: v20.12.2
文章目录
- Electron入门项目及打包
- 1. 初始化 npm 项目
- 2. 安装 electron
- 3. 编写electron程序
- 4. 运行
- 5. 打包
- 5.1 electron-builder打包
- 5.2 手动打包
- 5.3 不打包直接运行
1. 初始化 npm 项目
mkdir my-electron-app && cd my-electron-app
npm init
2. 安装 electron
npm install -g cnpm --registry=https://registry.npmmirror.com
cnpm install electron --save-dev
3. 编写electron程序
- index.js
const { app, BrowserWindow } = require('electron/main')const createWindow = () => {const win = new BrowserWindow({width: 800,height: 600})win.loadFile('index.html')
}app.whenReady().then(() => {createWindow()
})
- index.html
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>Hello from Electron renderer!</title>
</head><body><h1>Hello from Electron renderer!</h1>
</body></html>
- package.json
{"name": "electrontest","version": "1.0.0","description": "","main": "index.js","scripts": {"start": "electron .","test": "echo \"Error: no test specified\" && exit 1"},"author": "","license": "ISC","devDependencies": {"electron": "^30.1.1"}
}
4. 运行
npm run start
5. 打包
5.1 electron-builder打包
-
安装electron-builder
cnpm install electron-builder --save-dev
-
修改package.json
{"name": "electrontest","version": "1.0.0","description": "","main": "index.js","scripts": {"start": "electron .","build": "electron-builder","test": "echo \"Error: no test specified\" && exit 1"},"author": "","license": "ISC","devDependencies": {"electron": "^30.1.1","electron-builder": "^24.13.3"}
}
- 打包
npm run build
- 运行
cd dist/win-unpacked
electrontest.exe
5.2 手动打包
- 安装asar
npm install -g asar
asar -V
v3.2.0
- 打包源码到app.asar
新建pack文件夹,将index.js index.html package.json拷贝到pack文件
mkdir pack
asar ./ app.asar
-
将app.asar放到electron目录的resources文件夹中
-
运行
electron
5.3 不打包直接运行
v30.1.1 运行文件优先级:
app.asar > app文件夹 > default_app.asar
By default Electron will search in the following order app.asar
-> app
-> default_app.asar
。
electron\shell\common\node_bindings.cc
const std::vector<std::string> search_paths = {"app.asar", "app","default_app.asar"};
因此,直接将index.js index.html package.json拷贝electron目录的resources文件夹中即可直接运行。
目录结构如下
$ tree
.
+--- chrome_100_percent.pak
+--- chrome_200_percent.pak
+--- d3dcompiler_47.dll
+--- electron.exe
+--- ffmpeg.dll
+--- icudtl.dat
+--- libEGL.dll
+--- libGLESv2.dll
+--- LICENSE
+--- LICENSES.chromium.html
+--- locales
+--- resources
| +--- app
| | +--- index.html
| | +--- index.js
| | +--- package.json
+--- resources.pak
+--- snapshot_blob.bin
+--- v8_context_snapshot.bin
+--- version
+--- vk_swiftshader.dll
+--- vk_swiftshader_icd.json
+--- vulkan-1.dll
这篇关于Electron入门项目及打包的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!