由于长时间没有接过electron的项目,本次搭建时间花费了两天,所以记下来以备后面使用 2023/11/22
一、使用 vite 模板搭建 vue3 + ts 项目
pnpm create vite my-vue-app --template vue-ts
安装 并测试是否安装成功
cd my-project
pnpm install
pnpm run dev
二、安装
- electron : 基础包
- electron-builder: 打包工具
- electron-devtools-installer: 调试工具
- vite-plugin-electron: electron ➡️ vite 集成工具包,热启动、热重载 electron
pnpm install electron electron-builder electron-devtools-installer vite-plugin-electron -D
如果安装出现 ‘postinstall’下载不成功,大概率是网路问题,配置pnpm
pnpm config set electron_mirror=https://registry.npmmirror.com/-/binary/electron/
三、配置electron
1-3 摘抄 vite-plugin-electron 官方文档
-
vite-plugin-electron 添加到 vite.config.ts 插件里
import electron from 'vite-plugin-electron' export default { plugins: [ electron({ entry: 'electron/main.ts', }), ], }
-
创建 electron/main.ts 主进程文件
import { app, BrowserWindow } from 'electron' app.whenReady().then(() => { const win = new BrowserWindow({ title: 'Main window', }) // You can use `process.env.VITE_DEV_SERVER_URL` when the vite command is called `serve` if (process.env.VITE_DEV_SERVER_URL) { win.loadURL(process.env.VITE_DEV_SERVER_URL) } else { // Load your file win.loadFile('dist/index.html'); } })
-
添加入口文件地址到 package.json
{ + "main": "dist-electron/main.js" }
-
配置打包命令 package.json
# 脚本 添加electron打包命令 electron-builder "scripts": { + "build": "vue-tsc && vite build && electron-builder" }
# 添加打包配置 可添加appid 之类的,也可在根目录创建文件 electron-builder.json5 👇附件一 + "build": { + "files": [ + "dist", + "dist-electron" + ], + "directories": { + "output": "release/${version}" + } +}
-
electron不支持 model 模式 package.json
# 移除相关配置 { - "type": "module" }
-
配置Ts文件 tsconfig.json
# 新增 electron/*.ts "include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue", "electron/*.ts"],
四、其他
electron-builder.json5 👇附件一 打包配置文件
打包的时候会检测 package.json 的 build 字段或者 这个文件
/**
* @see https://www.electron.build/configuration/configuration
*/
{
"$schema": "https://raw.githubusercontent.com/electron-userland/electron-builder/master/packages/app-builder-lib/scheme.json",
"appId": "YourAppID",
"asar": true,
"productName": "YourAppName",
"directories": {
"output": "release/${version}"
},
"files": [
"dist",
"dist-electron"
],
"mac": {
"target": [
"dmg"
],
"artifactName": "${productName}-Mac-${version}-Installer.${ext}"
},
"win": {
"target": [
{
"target": "nsis",
"arch": [
"x64"
]
}
],
"artifactName": "${productName}-Windows-${version}-Setup.${ext}"
},
"nsis": {
"oneClick": false,
"perMachine": false,
"allowToChangeInstallationDirectory": true,
"deleteAppDataOnUninstall": false
},
"linux": {
"target": [
"AppImage"
],
"artifactName": "${productName}-Linux-${version}.${ext}"
}
}