前言
Electron是一個(gè)使用 JavaScript万搔、HTML 和 CSS 構(gòu)建桌面應(yīng)用程序的框架跟继。 嵌入 Chromium 和 Node.js 到 二進(jìn)制的 Electron 允許您保持一個(gè) JavaScript 代碼代碼庫(kù)并創(chuàng)建 在Windows上運(yùn)行的跨平臺(tái)應(yīng)用 macOS和Linux——不需要本地開(kāi)發(fā) 經(jīng)驗(yàn)柄沮。
electron搭建了一個(gè)殼,集成了chromium和node環(huán)境,業(yè)務(wù)邏輯只需要按vue寫(xiě)法即可。
方式一
直接使用electron-vue邻吭,具體內(nèi)容見(jiàn)文檔,優(yōu)點(diǎn)是配置齊全宴霸,即開(kāi)即用囱晴。缺點(diǎn)是很多配置已經(jīng)固定,比如eslint瓢谢,如果跟自己的開(kāi)發(fā)習(xí)慣不匹配的話畸写,需要做調(diào)整,另外electron的版本比較老氓扛。
方式二
vue-cli + electron艺糜,目前是我采用的方式。
搭建vue項(xiàng)目
此處不多做介紹幢尚,直接看文檔,我使用的是vite+vue3翅楼,有需要的可以去看文檔
安裝electron
npm i -D electron
配置electron入口
新建electron文件夾
代碼結(jié)構(gòu)如圖
// main.js
const { app, BrowserWindow } = require('electron');
const getMenuPersonal = require('./menu');
const getWindow = require('./window');
app.whenReady().then(() => {
let win = new getWindow().createWindow(); //創(chuàng)建窗口
new getMenuPersonal(win).createMenu(); //創(chuàng)建工具欄
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) new getWindow().createWindow();
});
// window.js
const windowStateKeeper = require('electron-window-state');
const path = require('path');
const { Menu, BrowserWindow, Tray, app } = require('electron');
const { join } = require('path');
process.env.DIST = join(__dirname, '../../');
const indexHtml = join(process.env.DIST, 'dist/index.html');
/**
* 創(chuàng)建窗口對(duì)象*/
class Window {
win = null;
getWindowState() {
// 配置electron-window-state插件,獲取窗口option
let win;
const mainWindowState = windowStateKeeper({
defaultWidth: 1000,
defaultHeight: 800
});
let { width, height } = mainWindowState;
const options = {
width,
height,
devTools: true,
show: false,
// icon: path.resolve(__dirname, '../log.ico'),
webPreferences: {
// nodeIntegration:true, //集成node api
// contextIsolation:false //關(guān)閉上下文隔離尉剩,配合nodeIntegration,可以賦予在render進(jìn)程中寫(xiě)node代碼的能力
preload: path.resolve(__dirname, '../preload/preload.js') //預(yù)加載的js文件
// webSecurity: false, // 同源策略
}
};
win = new BrowserWindow(options);
mainWindowState.manage(win);
return win;
}
createContextMenu(contents) {
// 創(chuàng)建右鍵菜單
let contextMenu = Menu.buildFromTemplate([{ label: 'Item 1' }, { role: 'editMenu' }]);
contents.on('context-menu', (e, params) => {
contextMenu.popup();
});
}
createTray() {
// 創(chuàng)建托盤(pán)
let trayMenu = Menu.buildFromTemplate([{ label: 'Item 1' }, { role: 'quit' }]);
let tray = new Tray(path.resolve(__dirname, '../trayTemplate.png'));
tray.setToolTip('Tray details');
tray.on('click', e => {
console.log(e);
if (e.shiftKey) {
app.quit();
} else {
this.win.isVisible() ? this.win.hide() : this.win.show();
}
});
tray.setContextMenu(trayMenu);
}
async createWindow() {
this.win = this.getWindowState();
this.createTray();
if (app.isPackaged) {
this.win.loadFile(indexHtml);
// this.win.loadURL(' https://www.baidu.com/');
} else {
this.win.loadURL('http://localhost:3004');
}
//等待dom渲染后打開(kāi)窗口
this.win.on('ready-to-show', () => {
this.win.show();
});
this.win.on('closed', () => {
this.win = null;
});
let contents = this.win.webContents;
contents.openDevTools();
// 開(kāi)啟vue-devtools
// await session.defaultSession.loadExtension(path.join(__dirname, '../../node_modules/vue-devtools/vender'));
this.createContextMenu(contents);
this.createTray();
return this.win;
}
}
module.exports = Window;
創(chuàng)建窗口需要添加依賴 electron-window-state
npm i electron-window-state
修改配置package.json
- 由于electron使用node模塊毅臊,需要修改
"type": "commonjs"
- 配置electron入口
"main": "electron/main/main.js"
- 添加啟動(dòng)script
"start": "electron --inspect=3004 ."
啟動(dòng)
先啟動(dòng)vue項(xiàng)目
npm run dev
然后啟動(dòng)electron
npm run start
到此理茎,基礎(chǔ)配置已經(jīng)完成。
問(wèn)題
- 安裝electron的過(guò)程當(dāng)中管嬉,有可能會(huì)出現(xiàn)下載失敗皂林,這種情況寫(xiě)可以配置npm源地址,具體內(nèi)容見(jiàn)文檔
- 生成托盤(pán)的圖片加載失敗
Failed to load image from path ?xxx
蚯撩,此種情況是圖片格式不對(duì)础倍,可以去iconfont里去下載,尺寸選16即可 - 使用vue-devtools胎挎,由于較新版本的electron中
BrowserWindow.addDevToolsExtension
接口已經(jīng)廢棄沟启,因此網(wǎng)上有些回答BrowserWindow.addDevToolsExtension(xxx)
會(huì)報(bào)錯(cuò)TypeError: electron.BrowserWindow.addDevToolsExtension is not a function
忆家,官網(wǎng)有提供替換接口session.loadExtension(path)
,可以將vue-devtools下載到本地引入德迹。
我這里使用了@vue/devtools
// 安裝
npm i -D @vue/devtools
// 使用
./node_modules/.bin/vue-devtools