Vue 与 Electron 结合开发桌面应用

发布于:2025-02-10 ⋅ 阅读:(156) ⋅ 点赞:(0)

1. 引言

  • 1.1 什么是 Electron?
    • Electron 是一个使用 JavaScript、HTML 和 CSS 构建跨平台桌面应用程序的框架。它结合了 Chromium 渲染引擎和 Node.js 运行时,使得开发者可以使用 Web 技术创建原生桌面应用。
  • 1.2 为什么选择 Vue.js 和 Electron?
    • Vue.js 是一个渐进式 JavaScript 框架,易于上手且功能强大。结合 Electron,可以快速构建出美观且功能丰富的桌面应用。
  • 1.3 目标读者
    • 本文适合对 Vue.js 有一定了解,并希望学习如何使用 Electron 开发桌面应用的开发者。

2. 环境准备

  • 2.1 安装 Node.js 和 npm

    • 访问 Node.js 官网 下载并安装最新版本的 Node.js,npm 会随 Node.js 一起安装。
  • 2.2 安装 Vue CLI

    npm install -g @vue/cli
    
  • 2.3 安装 Electron

    npm install -g electron
    

3. 创建 Vue 项目

  • 3.1 使用 Vue CLI 创建项目

    vue create my-electron-app
    cd my-electron-app
    
  • 3.2 项目结构介绍

    • public:存放静态资源文件。
    • src:存放源代码文件。
    • package.json:项目配置文件。
  • 3.3 运行 Vue 项目

    npm run serve
    

4. 集成 Electron

  • 4.1 初始化 Electron 项目

    • 在 Vue 项目根目录下创建 main.js 文件。
    const {
          app, BrowserWindow } = require('electron');
    const path = require('path');
    
    function createWindow() {
         
      const win = new BrowserWindow({
         
        width: 800,
        height: 600,
        webPreferences: {
         
          preload: path.join(__dirname, 'preload.js'),
          nodeIntegration: true,
          contextIsolation: false,
        },
      });
    
      win.loadURL('http://localhost:8080');
    }
    
    app.whenReady().then(() => {
         
      createWindow();
    
      app.on('activate', () => {
         
        if (BrowserWindow.getAllWindows().length === 0) {
         
          createWindow();
        }
      });
    });
    
    app.on('window-all-closed', () => {
         
      if (process.platform !== 'darwin') {
         
        app.quit();
      }
    });
    
  • 4.2 创建主进程文件(main.js)

    • 上面已经创建了 main.js 文件,它是 Electron 应用的入口文件。
  • 4.3 配置 Electron 打包工具

    • package.json 中添加 Electron 的启动脚本。
    "scripts": {
         
      "serve": "vue-cli-service serve",
      "build": "vue-cli-service build",
      "lint": "vue-cli-service lint",
      "electron:serve": "electron ."
    }
    
  • 4.4 运行 Electron 应用

    npm run serve
    npm run electron:serve
    

5. 项目结构优化

  • 5.1 分离主进程和渲染进程代码

    • 将主进程和渲染进程的代码分开,使项目结构更清晰。
    • 主进程:main.js
    • 渲染进程:Vue 项目
  • 5.2 使用 Webpack 打包 Electron 应用

    • 安装 electron-buildervue-cli-plugin-electron-builder
    npm install --save-dev electron-builder
    vue add electron-builder
    
  • 5.3 配置 Vue CLI 与 Electron 的集成

    • vue.config.js 中配置打包选项。
    module.exports = {
         
      pluginOptions: {
         
        electronBuilder: {
         
          mainProcessFile: 'src/main.js',
          rendererProcessFile: 'src/renderer.js',
          nodeIntegration: true,
          contextIsolation: 

网站公告

今日签到

点亮在社区的每一天
去签到