使用 Electron打包markdown编辑器。
准备项目结构
markdown-editor/
├── index.html (之前的编辑器代码)
├── main.js
├── package.json
└── icons/ (可选)
创建 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
| const { app, BrowserWindow } = require('electron') const path = require('path')
app.commandLine.appendSwitch('disable-3d-apis'); app.commandLine.appendSwitch('disable-gpu'); function createWindow() { const win = new BrowserWindow({ width: 1200, height: 800, webPreferences: { nodeIntegration: true, contextIsolation: false }, icon: path.join(__dirname, 'icons/icon.ico') })
win.loadFile('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() } })
|
初始化项目
在项目目录运行:
1 2
| npm init -y npm install electron --save-dev
|
修改 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
| { "name": "markdown-editor", "version": "1.0.0", "main": "main.js", "scripts": { "start": "electron .", "pack": "electron-builder --dir", "dist": "electron-builder" }, "devDependencies": { "electron": "36.1.0", "electron-builder": "26.0.12" }, "build": { "appId": "com.example.markdowneditor", "win": { "target": "nsis", "icon": "icons/icon.ico", "compression": "maximum", "asar": true, "files": [ "!**/node_modules/electron-*", "!**/node_modules/*/{test,example,doc}", "!**/*.{map,ts,md}" ] } } }
|
安装 electron-builder 并打包
1 2
| npm install electron-builder npm run dist
|
打包完成后,安装程序会在 dist 文件夹中生成。
由于npm install
安装 Electron 时卡住,使用 Yarn 替代 npm
1 2 3
| npm install -g yarn yarn config set registry https: yarn
|
最后执行:
npm run dist
得到exe安装包,82M,安装后,目录288M。
为什么 Electron 应用体积大?
- Chromium 内核
Electron 捆绑了完整的 Chromium 浏览器内核(约120-150MB),这是支持网页渲染的核心。
- Node.js 运行时
包含完整的 Node.js 环境(约40-60MB),用于后端逻辑执行。
- V8 引擎
JavaScript 引擎的二进制文件(约20-30MB)。
- 应用代码和依赖
代码、node_modules 以及 Electron 自身依赖(约30-50MB)。
- 默认包含所有平台支持
即使只打包 Windows 版本,默认配置可能包含跨平台冗余文件。
预览:markdown编辑器