一、创建 Vue 项目
1. 创建项目
pnpm create vite
2. 安装依赖
cd excel-electron
pnpm install
3. 运行项目
pnpm dev
二、添加 Electron
1. 安装 electron
pnpm add electron -D
2. 修改 package.json
添加入口 js 和执行命令。
{"main": "dist-electron/index.js","scripts": {"start": "electron ."}}
3. 添加主进程文件
dist-electron/index.js 创建窗口。为什么不是 ts 呢,因为 electron 不支持 ts。
import { app, BrowserWindow } from "electron";const createWindow = () => {const win = new BrowserWindow({webPreferences: {contextIsolation: false, // 是否开启隔离上下文nodeIntegration: true, // 渲染进程使用Node APIpreload: "./preload.js", // 需要引用js文件},});let url = "http://localhost:5173"; // 本地启动的vue项目路径。注意:vite版本3以上使用的端口5173;版本2用的是3000win.loadURL(url);win.webContents.openDevTools();};app.whenReady().then(() => {createWindow(); // 创建窗口});
4. 添加预加载脚本文件
dist-electron/preload.js 在渲染进程调用主进程 API。
import os from "os";console.log("platform", os.platform());
5. 运行 electron 命令
pnpm start
三、Vue 集成 Electron
1. 安装依赖
集成 Vite 和 Electron,方便后续在渲染进程中使用 Node API 或 Electron API
pnpm add vite-plugin-electron -D
pnpm add vite-plugin-electron-renderer -D
2. 编辑 vite.config.ts
import { defineConfig } from "vite";import vue from "@vitejs/plugin-vue";import electron from "vite-plugin-electron";import electronRenderer from "vite-plugin-electron-renderer";export default defineConfig({plugins: [vue(),electron([{entry: "electron/index.ts",},{entry: "electron/preload.ts",},]),electronRenderer(),],build: {emptyOutDir: false,outDir: "dist-electron",},});
3. 编辑 package.json
{"name": "excel-electron","private": true,"version": "0.0.0","main": "dist-electron/index.js","scripts": {"dev": "vite","start": "electron .","build": "vue-tsc -b && vite build","preview": "vite preview"},"dependencies": {"vue": "^3.5.13"},"devDependencies": {"@types/node": "^22.10.2","@vitejs/plugin-vue": "^5.2.1","@vue/tsconfig": "^0.7.0","electron": "^33.2.1","typescript": "~5.6.2","vite": "^6.0.5","vite-plugin-electron": "^0.29.0","vite-plugin-electron-renderer": "^0.14.6","vue-tsc": "^2.2.0"}}
4. 运行命令
pnpm dev