vue2(webpack)集成electron和 electron 打包

发布于:2025-04-05 ⋅ 阅读:(13) ⋅ 点赞:(0)

前言

之前发过一篇vue集成electron的文章,但是用vue3+vite实现的,在vue2+webpack工程可能不适用,所以这篇文章就主要介绍vue2+webpack集成electron方法

创建项目

vue create vue-electron-demo

目录架构

vue-electron-demo/
├── src/               
├── electron/           # Electron
│   ├── main/           # 主进程代码
│   ├── preload/        # 预加载脚本
│   └── resources/      # 图标等资源
├── src-shared/         # 跨平台共享代码
├── public/
└── vue.config.js  

安装依赖

注意兼容问题,且node版本太低如nodejs14以下不行

npm install --save-dev electron vue-cli-plugin-electron-builder
npm install --save path-browserify

实现代码

vue.config.js

const { defineConfig } = require('@vue/cli-service')
const path = require('path')

module.exports = defineConfig({
  transpileDependencies: true,
  publicPath: process.env.NODE_ENV === 'production' ? './' : '/',
  configureWebpack: {
    resolve: {
      alias: {
        '@shared': path.resolve(__dirname, 'src-shared'),
        'path': 'path-browserify'  // Web 端兼容 path
      }
    }
  },
  pluginOptions: {
    electronBuilder: {
      mainProcessFile: './electron/main/index.js',
      preload: 'electron/preload/preload.js',
      builderOptions: {
        productName: 'ElectronDemo',
        appId: 'com.example.electrondemo',
        win: {
          icon: 'electron/resources/icon.ico',
          target: 'nsis'
        },
        files: [
          "**/*",
          "dist/**/*",
          {
            from: "electron/resources",
            to: "resources"  // 资源文件打包
          }
        ],
        // 关键:适配打包规则
        asar: true,
        nodeGypRebuild: false,
        buildDependenciesFromSource: false,
        extraResources: [
          {
            from: "dist",          // Vue 构建输出的目录
            to: "dist",            // 目标路径(位于 resources 下)
            filter: ["**/*"]
          }
        ]
      }
    }
  }
})

修改package.json

"scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint",
    "electron:build": "vue-cli-service electron:build  mode=ELECTRON",
    "electron:serve": "vue-cli-service electron:serve"
  },
  "main": "background.js",

electron\main\index.js

const { app, BrowserWindow } = require('electron')
const path = require('path')

// 禁用旧版安全警告(开发环境)
process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = 'true'

// 窗口创建函数(适配 Electron 21)
function createWindow() {
  const win = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      nodeIntegration: false,          // 必须禁用
      contextIsolation: true,          // 强制启用
      preload: path.join(__dirname, '../preload/preload.js')
    }
  })

  // 加载页面(区分开发/生产环境)
  if (process.env.WEBPACK_DEV_SERVER_URL) {
    win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    win.webContents.openDevTools()
  } else {
    win.loadFile(path.join(__dirname, '..', 'dist', 'index.html'))
  }
}

// 生命周期管理
app.whenReady().then(createWindow)
app.on('window-all-closed', () => process.platform !== 'darwin' && app.quit())
app.on('activate', () => BrowserWindow.getAllWindows().length === 0 && createWindow())

electron\preload\preload.js

const { contextBridge, ipcRenderer } = require('electron')

// 安全暴露 API 给渲染进程(Electron 21+ 强制要求)
contextBridge.exposeInMainWorld('electronAPI', {
  platform: process.platform,
  showDialog: (options) => ipcRenderer.invoke('dialog:show', options)
})

运行脚本

开发环境 (本地运行)

npm run electron:serve

生产环境 (打包)

npm run electron:build

打包结果

在这里插入图片描述
打开后项目也能正常运行


网站公告

今日签到

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