搭建electron+vue项目

2023-11-20  本文已影响0人  drneilc

前言

Electron是一个使用 JavaScript、HTML 和 CSS 构建桌面应用程序的框架。 嵌入 ChromiumNode.js 到 二进制的 Electron 允许您保持一个 JavaScript 代码代码库并创建 在Windows上运行的跨平台应用 macOS和Linux——不需要本地开发 经验。
electron搭建了一个壳,集成了chromium和node环境,业务逻辑只需要按vue写法即可。

方式一

直接使用electron-vue,具体内容见文档,优点是配置齐全,即开即用。缺点是很多配置已经固定,比如eslint,如果跟自己的开发习惯不匹配的话,需要做调整,另外electron的版本比较老。

方式二

vue-cli + electron,目前是我采用的方式。

搭建vue项目

此处不多做介绍,直接看文档,我使用的是vite+vue3,有需要的可以去看文档

安装electron
npm i -D electron
配置electron入口

新建electron文件夹

image.png

代码结构如图

// main.js
const { app, BrowserWindow } = require('electron');
const getMenuPersonal = require('./menu');
const getWindow = require('./window');

app.whenReady().then(() => {
    let win = new getWindow().createWindow(); //创建窗口
    new getMenuPersonal(win).createMenu(); //创建工具栏
});

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');
/**
 * 创建窗口对象*/
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  //关闭上下文隔离,配合nodeIntegration,可以赋予在render进程中写node代码的能力
                preload: path.resolve(__dirname, '../preload/preload.js') //预加载的js文件
                // webSecurity: false, // 同源策略
            }
        };

        win = new BrowserWindow(options);
        mainWindowState.manage(win);

        return win;
    }

    createContextMenu(contents) {
        //    创建右键菜单
        let contextMenu = Menu.buildFromTemplate([{ label: 'Item 1' }, { role: 'editMenu' }]);
        contents.on('context-menu', (e, params) => {
            contextMenu.popup();
        });
    }

    createTray() {
        // 创建托盘
        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渲染后打开窗口
        this.win.on('ready-to-show', () => {
            this.win.show();
        });
        this.win.on('closed', () => {
            this.win = null;
        });

        let contents = this.win.webContents;

        contents.openDevTools();

        // 开启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;

创建窗口需要添加依赖 electron-window-state

npm i electron-window-state
修改配置package.json
启动

先启动vue项目

npm run dev

然后启动electron

npm run start

到此,基础配置已经完成。

问题

  1. 安装electron的过程当中,有可能会出现下载失败,这种情况写可以配置npm源地址,具体内容见文档
  2. 生成托盘的图片加载失败 Failed to load image from path �xxx,此种情况是图片格式不对,可以去iconfont里去下载,尺寸选16即可 image.png
  3. 使用vue-devtools,由于较新版本的electron中BrowserWindow.addDevToolsExtension接口已经废弃,因此网上有些回答BrowserWindow.addDevToolsExtension(xxx)会报错TypeError: electron.BrowserWindow.addDevToolsExtension is not a function,官网有提供替换接口session.loadExtension(path),可以将vue-devtools下载到本地引入。
    我这里使用了@vue/devtools
// 安装 
npm i -D @vue/devtools

// 使用
./node_modules/.bin/vue-devtools
上一篇下一篇

猜你喜欢

热点阅读