前端Web打包成可執行程式
工作需要用到了這個技術,這裡記錄一下,實現過程:
首先安裝打包環境:
第一步,安裝Nodejs;(nodejs的官網連結:https://nodejs.org/zh-cn/,選擇你想要的版本)
安裝過程可參考這篇文章:(不參考安裝過程,直接預設安裝也沒問題)
https://segmentfault.com/a/1190000023390756
第二步,安裝electron;
win+R開啟命令列,然後輸入:npm install electron -g,點選回車,需要等待一段時間
然後,找到你的前端專案,新建立兩個檔案:main.js、package.json
main.js中輸入一下內容:
// main.js
const {app, BrowserWindow} = require('electron') const path= require('path') const url = require('url') // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is garbage collected. let win function createWindow () { // Create the browser window. win = new BrowserWindow({width: 800, height: 600})// and load the index.html of the app. win.loadURL(url.format({ pathname: path.join(__dirname, 'mian.html'),// 此處的html為你自己的專案的主頁面的名稱 protocol: 'file:', slashes: true })) // Open the DevTools. // win.webContents.openDevTools() // Emitted when the window is closed. win.on('closed', () => {// Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. win = null }) } // This method will be called when Electron has finished // initialization and is ready to create browser windows. // Some APIs can only be used after this event occurs. app.on('ready', createWindow) // Quit when all windows are closed. app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() } }) app.on('activate', () => { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (win === null) { createWindow() } }) // In this file you can include the rest of your app's specific main process // code. You can also put them in separate files and require them here.
package.json
{ "name": "app", "version": "0.1.0", "main": "main.js"// 此處的main.js就是上文中的那個檔案,使用時請將這個註釋刪掉 }
第三步,完成上一步的工作之後,開啟命令列,將路徑切換到當前專案的主目錄下,
這是我的路徑,建議使用全英文路徑,不確定中文路徑是否會有影響。
第四步:在當前的命令列中輸入:
npm install electron-packager -g
安裝打包工具;
安裝過程需要持續一段時間,休息一下。
第五步:在當前的命令列中輸入:
electron-packager . app --win --out Exe --arch=x64 --electron-version 11.1.1 --overwrite --ignore=node_modules
electron-packager . 可執行檔案的檔名 --win --out 打包成的資料夾名 --arch=x64位還是32位 --electron-version 版本號 --overwrite --ignore=node_modules
注意:--electron-version 版本號,這個版本號就是你之前安裝的那個版本號;
打包過程需要持續一段時間,等一會兒。
最終會在當前資料夾下輸出一個新的目錄:
進入這個路徑,找到生成的Exe檔案,這個就是web工程打包出來的可執行檔案。
注意:這個可執行檔案的正常執行依賴於resources目錄下的檔案。
實現過程參考了:
https://blog.csdn.net/a727911438/article/details/70834467
https://segmentfault.com/a/1190000023390756
另外:下次打包的時候可以直接拷貝當前專案下的main.js以及package.json,稍作修改即可使用,打包過程重複上述步驟即可。