一个vue3和electron最基本的环境搭建步骤如下:
// 安装 vite + vue3
npm create vue@latest
// 安装electron,然后在根目录下创建main.js文件, package.json也要配置main:main.js
npm i electron -D
// 安装nodemon, 监听js css html vue文件发生变化后重新渲染,然后配置package.json
npm i nodemon -D
"scripts": {
"start": "nodemon --exec electron . --watch ./ --ext .js,.html,.css,.vue"
}
// 安装electron-win-state,记录窗口停留的位置
npm i electron-win-state -D
// 创建preload文件夹,创建一个index.js
// 完善一下官网的案例
app.whenReady().then(() => {
createWindow()
app.on('activate', () => {
// const {BrowserWindow} = require('electron')
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit()
})
具体项目信息查看本地上传的资源, 这里就的代码只拷贝一部分比较重要的
// main.js
const {app, BrowserWindow} = require('electron')
const path = require('path')
const WinState = require('electron-win-state').default
function createWindow() {
const winState = new WinState({
defaultWidth: 1000,
defaultHeight: 800
})
const win = new BrowserWindow({
...winState.winOptions,
webPreferences: {
preload: path.resolve(__dirname, 'preload/index.js'),
sandbox: false
},
})
win.loadURL('http://localhost:5173')
winState.manage(win)
}
app.whenReady().then(() => {
createWindow();
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit()
})
// package.json
{
"name": "readit",
"version": "0.0.0",
"description": "first electron app",
"private": true,
"main": "main.js",
"scripts": {
"dev": "vite",
"build": "run-p type-check \"build-only {@}\" --",
"preview": "vite preview",
"build-only": "vite build",
"type-check": "vue-tsc --build --force",
"start": "nodemon --exec electron . --watch ./ --ext .js,.html,.css,.vue"
},
"dependencies": {
"vue": "^3.5.12"
},
"devDependencies": {
"@tsconfig/node22": "^22.0.0",
"@types/node": "^22.9.0",
"@vitejs/plugin-vue": "^5.1.4",
"@vue/tsconfig": "^0.5.1",
"electron": "^33.2.0",
"electron-win-state": "^1.1.22",
"nodemon": "^3.1.7",
"npm-run-all2": "^7.0.1",
"typescript": "~5.6.3",
"vite": "^5.4.10",
"vite-plugin-vue-devtools": "^7.5.4",
"vue-tsc": "^2.1.10"
}
}
// index.html
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="UTF-8">
<link rel="icon" href="/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 去掉窗口的Content-Security-Policy警告,告诉该页面的内容是使用本地的 -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src 'self' data:; script-src 'self'; style-src 'self' 'unsafe-inline'">
<title>Vite App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>