将 Vue 3 + Vite + TS 项目打包为 .exe 文件
使用 electron-builder打包:
一、安装依赖
npm install electron electron-builder --save-dev
二、创建 Electron 入口文件:在项目根目录下创建 electron/main.js 文件
import { app, BrowserWindow } from 'electron';
import path from 'path';
import { fileURLToPath } from 'url';// 兼容 ESM 的 __dirname
const __dirname = path.dirname(fileURLToPath(import.meta.url));let win: BrowserWindow | null = null;function createWindow() {win = new BrowserWindow({width: 1920,height: 1080,webPreferences: {nodeIntegration: true,contextIsolation: false,},});// 开发环境下加载 Vite 开发服务器if (process.env.NODE_ENV === 'development') {win.loadURL('http://localhost:5173');win.webContents.openDevTools();} else {// 生产环境下加载打包后的文件win.loadFile(path.join(__dirname, '../dist/index.html'));}
}app.whenReady().then(createWindow);// 所有窗口关闭时退出应用(macOS 除外)
app.on('window-all-closed', () => {if (process.platform !== 'darwin') app.quit();
});// macOS 下点击 Dock 图标重新打开窗口
app.on('activate', () => {if (BrowserWindow.getAllWindows().length === 0) createWindows();
});// 只在开发模式下启用热重载
if (process.env.NODE_ENV === 'development') {// 开发模式下的热重载逻辑require('electron-reload')(__dirname, {electron: path.join(__dirname, '..', 'node_modules', '.bin', 'electron'),});
}
三、修改 package.json:添加/修改以下配置:
{"main": "electron/main.js","scripts": {"electron:serve": "vite build && electron .","electron:build": "vite build && electron-builder --dir"},"build": {"productName": "test","files": ["dist/**/*","electron/**/*"],"win": {"target": "nsis"},"mac": {"target": "dmg"},"linux": {"target": "AppImage"}}
}
四、构建应用
npm run electron:build
可能会遇到的问题:
1、打包后出现白屏或者黑屏