Vue + Electron 跨平台打包完整指南
Vue + Electron 跨平台打包完整指南
1. 配置文件说明
1.1 package.json 配置详解
1 | { |
1.2 electron/main.ts 配置详解
1 | import { app, BrowserWindow, globalShortcut } from 'electron' |
1.3 vite.config.ts 配置详解
1 | import { defineConfig } from 'vite' |
2. 打包命令使用
2.1 开发模式
1 | # 启动开发服务器 |
2.2 生产构建
1 | # Mac 构建 |
2.3 代理设置(如需要)
1 | export https_proxy=http://127.0.0.1:7890 http_proxy=http://127.0.0.1:7890 all_proxy=socks5://127.0.0.1:7890 |
3. 常见问题解决
3.1 白屏问题
检查路径配置:
- vite.config.ts 中
base: './'
- main.ts 中路径使用
path.join()
- vite.config.ts 中
配置网页安全性:
1
2
3
4
5webPreferences: {
nodeIntegration: true,
contextIsolation: false,
webSecurity: false
}
3.2 开发工具问题
注意之前由于loadFile错误导致无法启动开发工具,并不是本身代码的问题
确保配置:
1
2
3webPreferences: {
devTools: true
}注册快捷键:
1
2
3globalShortcut.register('CommandOrControl+Shift+I', () => {
win.webContents.toggleDevTools()
})
3.3 跨平台构建注意事项
macOS:
- 签名配置:
"identity": null
- DMG 格式:
"target": ["dmg"]
- 签名配置:
Windows:
NSIS 配置:
"oneClick": false
权限级别:
"requestedExecutionLevel": "asInvoker"
下载 NSIS 资源时遇到了网络问题,可以使用下面的命令,再执行build命令,当然可能只是当时网络波动了
1
sudo rm -rf node_modules/.cache/electron-builder &&sudo rm -rf release
通用:
- 使用相对路径
- 处理资源文件
- 错误处理机制
3.4 模块加载错误解决
具体报错:Uncaught ReferenceError: exports is not defined at index-BF1qxaNs.js:1:36,然后页面依旧是白屏
- package.json 中移除 “type”: “module”
- 使用 CommonJS 格式构建
- 确保所有路径使用相对路径
4. 最佳实践
- 文件组织
1
2
3
4
5project/
├── electron/ # Electron 主进程代码
├── src/ # 渲染进程代码(Vue)
├── dist/ # 构建输出
└── release/ # 打包输出
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 TEC!
评论