利用Electron將專案前端網頁打包成桌面應用
阿新 • • 發佈:2018-12-22
一、環境搭建
1.全域性安裝node.js
2.全域性安裝electron
npm install electron -g
3.準備好要打包的html/js/css等網頁檔案
二、進行打包
首先,我們要明白electron打包的檔案架構:
你的專案目錄/
├── package.json
├── main.js
└── index.html
在web專案目錄下分別建立package.json、main.js、index.html檔案
package.json中是一些配置性檔案,json格式,寫上如下程式碼:
{ "name" : "app-name", "version" : "0.1.0", "main" : "main.js" }
main.js中對應的是package.json中main的值,寫上如下程式碼:
const {app, BrowserWindow} = require('electron') const path = require('path') const url = require('url') let win function createWindow () { win = new BrowserWindow({width: 800, height: 600}) win.loadURL(url.format({ pathname: path.join(__dirname, 'index.html'), protocol: 'file:', slashes: true })) win.on('closed', () => { win = null }) } app.on('ready', createWindow) app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit() } }) app.on('activate', () => { if (win === null) { createWindow() } })
接下來在所要打包的專案目錄中開啟DOS介面,npm安裝electron-package:npm install electron-package -g
再接著輸入electron-package . (生成exe檔案的名字) --win --out (打包完資料夾的名字) -arch=×64 --electronVersion (electron的版本號) --overwrite --ignore=node_modules即可完成打包
最後進入打包資料夾,找到.exe檔案,點選開啟即可
三、注意事項
1.輸入打包命令時,千萬要注意所安裝的electron的版本。
2. .後面加生成exe檔案的名字要加空格
3.--electronVersion很多經驗文章都寫成了--version導致解壓報錯