雖然 B/S 是目前開發的主流,但是 C/S 仍然有很大的市場需求。受限于瀏覽器的沙盒限制,網頁應用無法滿足某些場景下的使用需求,而桌面應用可以讀寫本地文件、調用更多系統資源,再加上 Web 開發的低成本、高效率的優勢,這種跨平臺方式越來越受到開發者的喜愛。
Electron 是一個基于 Chromium 和 Node.js,使用 HTML、CSS 和 JavaScript 來構建跨平臺應用的跨平臺開發框架,兼容 Mac、Windows 和 Linux。目前,Electron 已經創建了包括 VScode 和 Atom 在內的大量應用。
一、準備工作
創建Electron跨平臺應用之前,需要先安裝一些常用的工具,如Node和Electron等。
- 安裝node在前說過就不詳細說了。
- 安裝Electron。
npm install -g electron
// 或者
cnpm install -g electron
// 驗證是否安裝成功
electron -v
二、創建項目
- 創建運行項目
Electron官方提高了一個簡單的項目,可以執行以下命令將項目克隆到本地。
git clone https://github.com/electron/electron-quick-start
- 安裝依賴
cd electron-quick-start
npm install
- 運行
npm start
三、更改內容
在我們的項目可以順利啟動以后,我們需要對項目做一些更改,來運行我們需要的內容。
- 放入靜態文件
在項目根目錄新建static文件夾,將靜態文件放入。 - 更改main.js
/*
* @Description: 主入口文件
* @Author: cuiht
* @Date: 2021-01-13 15:58:29
* @LastEditTime: 2021-01-14 15:04:16
*/
// Modules to control application life and create native browser window
const {
app,
globalShortcut,
screen,
dialog,
BrowserWindow,
Menu,
} = require("electron");
const path = require("path");
function createWindow() {
// 去除菜單欄
Menu.setApplicationMenu(null);
// 創建窗口
const mainWindow = new BrowserWindow({
width: screen.getPrimaryDisplay().workAreaSize.width * 0.9,
height: screen.getPrimaryDisplay().workAreaSize.height * 0.9,
fullscreen: true,
webPreferences: {
nodeIntegration: true,
preload: path.join(__dirname, "preload.js"),
},
});
// //配置ESC鍵退出全屏
globalShortcut.register("ESC", () => {
mainWindow.close();
});
// //配置F11切換全屏
// globalShortcut.register("F11", () => {
// mainWindow.setFullScreen(!mainWindow.isFullScreen());
// });
// 加載靜態文件
mainWindow.loadFile("static/index.html");
// 監聽窗口關閉
mainWindow.on("close", (e) => {
e.preventDefault();
dialog
.showMessageBox({
type: "info",
title: "提示",
defaultId: 0,
message: "確定要退出嗎?",
buttons: ["最小化", "退出"],
})
.then((result) => {
if (result.response === 0) {
e.preventDefault();
mainWindow.minimize();
} else {
app.exit(); //exit()直接關閉客戶端,不會執行quit();
}
})
.catch((err) => {
console.log(err);
});
});
// 監聽程序崩潰
mainWindow.webContents.on("crashed", () => {
const options = {
type: "error",
title: "進程崩潰了",
message: "這個進程已經崩潰.",
buttons: ["重載", "退出"],
};
recordCrash()
.then(() => {
dialog
.showMessageBox(options)
.then((result) => {
if (result.response === 0) {
reloadWindow(mainWindow);
} else {
app.exit();
}
})
.catch((err) => {
console.log(err);
});
})
.catch((e) => {
console.log("err", e);
});
});
}
// 崩潰日志請求
function recordCrash() {
return new Promise((resolve) => {
// 崩潰日志請求成功....
resolve();
});
}
// 重載窗口
function reloadWindow(mainWin) {
if (mainWin.isDestroyed()) {
app.relaunch();
app.exit(0);
} else {
BrowserWindow.getAllWindows().forEach((w) => {
if (w.id !== mainWin.id) w.destroy();
});
mainWin.reload();
}
}
// 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.whenReady().then(() => {
createWindow();
app.on("activate", function () {
// 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 (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on("window-all-closed", function () {
if (process.platform !== "darwin") app.quit();
// 注銷所有快捷鍵
globalShortcut.unregisterAll();
});
// 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.
四、打包為exe文件
- 安裝打包工具electron-packager
cnpm install electron-packager -g
- 打包
在項目根目錄運行
electron-packager . HelloWorld --platform=win32 --arch=x64 --icon=computer.ico --out=./out --asar --app-version=0.0.1 --overwrite --ignore=node_modules --electron-version 5.0.0
各個參數介紹:
HelloWorld :你將要生成的exe文件的名稱
--platform=win32:確定了你要構建哪個平臺的應用,可取的值有 darwin, linux, mac, win32
--arch=x64:決定了使用 x86 還是 x64 還是兩個架構都用
--icon=computer.ico:自定義設置應用圖標
--out=./out:指定打包文件輸出的文件夾位置,當前指定的為項目目錄下的out文件夾
--asar:該參數可以不加,如果加上,打包之后應用的源碼會以.asar格式存在,否則會以文件夾形式存在
--app-version=0.0.1:生成應用的版本號
--overwrite:覆蓋原有的build,讓新生成的包覆蓋原來的包
--ignore=node_modules:如果加上該參數,項目里node_modules模塊不會被打包進去
--electron-version 5.0.0:指定當前要構建的electron的版本,需要和當前的版本一致,具體可以在package.json文件中查看,可以不加該參數,如果不一致,會自動下載,不建議設置
- 注意事項
可以將打包命令寫入 package.json中方便后續開發。
eg:
"scripts": {
"start": "electron .",
"package": "electron-packager . HelloWorld --platform=win32 --arch=x64 --icon=computer.ico --out=./out --asar --app-version=0.0.1 --overwrite --ignore=node_modules"
},
然后運行
npm run package
在打包過程中如國提示下載文件,可以通過npm set ELECTRON_MIRROR=https://npm.taobao.org/mirrors/electron/
,將下載文件的地址設置到淘寶鏡像減少麻煩。
-
打包成功
打包后會生成如下文件夾,點擊運行HelloWorld.exe,就可以了。
文件目錄
效果圖
效果圖
參考文獻:electronjs
世界的模樣,取決于你凝視它的目光,自己的價值取決于你的追求與心態。一切美好的愿望,不是在等待中擁有,而是在奮斗中爭取!