Electron + ts + vue3 + vite 项目搭建
1.新建一个vite + ts + vue3的项目
npm create vite@latest my-vue-app
在创建选项中选择ts和vue选项。
之后,安装依赖之后试运行一下,出现一下页面意味着vite-vue项目创建成功。
2.安装electron的相关依赖
首先是electron本身
npm install electron -D
然后是打包工具
npm install electron-builder -D
再者是开发工具
npm install electron-devtools-installer -D
最后是配置文件
npm install vite-plugin-electron -D
3.配置electron
在项目的根目录下新建electron-main文件夹,之后新建index.ts,配置如下:
import { app, BrowserWindow } from "electron";
import * as path from "path";
// 本地启动的vue项目路径
const vueProjectAddress = "http://localhost:5173"
/**
* 创建一个新的窗口
*/
const createWindow = () =>{
const win = new BrowserWindow({
webPreferences: {
contextIsolation: false, // 是否开启隔离上下文
nodeIntegration: true, // 渲染进程使用Node API
},
});
if (app.isPackaged) {
win.loadFile(path.join(__dirname, "../index.html"));
} else {
win.loadURL(vueProjectAddress);
}
};
// 打开窗口
app.whenReady().then(() => {
createWindow(); // 创建窗口
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
// 关闭窗口
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
打开tsconfig.json,在include中增加配置"electron-main/**/*.ts"。
"include": [
"src/**/*.ts",
"src/**/*.d.ts",
"src/**/*.tsx",
"src/**/*.vue",
"electron-main/**/*.ts",
]
打开vite.config.ts,增加配置如下:
import electron from "vite-plugin-electron";
import electronRenderer from "vite-plugin-electron-renderer";
export default defineConfig({
plugins: [
vue(),
electron({
entry: "electron-main/index.ts", // 主进程文件
}),
electronRenderer(),
],
build: {
emptyOutDir: false, // 默认情况下,若 outDir 在 root 目录下,则 Vite 会在构建时清空该目录
},
})
打开package.json,增加以下配置:
{
"name": "my-vue-app",
"private": true,
"version": "0.0.0",
"main": "dist-electron/index.js", // 新增
"scripts": {
"dev": "vite",
"build": "vue-tsc && rimraf dist && vite build && electron-builder",
"preview": "vite preview"
},
// build 新增
"build": {
"appId": "com.smallpig.desktop",
"productName": "smallpig",
"asar": true,
"copyright": "Copyright © 2022 smallpig",
"directories": {
"output": "release/${version}"
},
"files": [
"dist"
],
"mac": {
"artifactName": "${productName}_${version}.${ext}",
"target": [
"dmg"
]
},
"win": {
"target": [
{
"target": "nsis",
"arch": [
"x64"
]
}
],
"artifactName": "${productName}_${version}.${ext}"
},
"nsis": {
"oneClick": false,
"perMachine": false,
"allowToChangeInstallationDirectory": true,
"deleteAppDataOnUninstall": false
},
// 新增
"publish": [
{
"provider": "generic",
"url": "http://127.0.0.1:8080"
}
],
"releaseInfo": {
"releaseNotes": "版本更新的具体内容"
}
},
"dependencies": {
"electron-devtools-installer": "^3.2.0",
"vue": "^3.2.45"
},
"devDependencies": {
"@vitejs/plugin-vue": "^4.0.0",
"electron": "^22.0.2",
"electron-builder": "^23.6.0",
"install": "^0.13.0",
"npm": "^9.3.0",
"polyfill-exports": "^0.4.0-beta.2",
"rimraf": "^4.1.0",
"typescript": "^4.9.3",
"vite": "^4.0.0",
"vite-plugin-electron": "^0.11.1",
"vite-plugin-electron-renderer": "^0.11.4",
"vue-tsc": "^1.0.11"
}
}
最后直接npm install dev就可以。