返回
零基础快速搭建Vite 2 + Vue 3 + Electron 桌面应用
前端
2024-01-19 03:22:07
前言
在现代前端工程化浪潮中,桌面应用开发正在蓬勃发展。Electron 框架以其跨平台、高性能和对 Web 技术的无缝集成而备受推崇。结合 Vite 2 的极速构建和 Vue 3 的响应式数据绑定,我们可以打造出兼具性能、效率和用户体验的桌面应用。
搭建环境
1. 安装 Node.js 和相关工具
- 安装 Node.js v16 或以上版本
- 安装 Vite 全局命令行工具:
npm install -g vite
- 安装 Electron 全局命令行工具:
npm install -g electron
2. 创建项目
- 创建一个新的项目目录
- 进入目录并初始化一个 Vue 3 项目:
vue create my-app --template vue-ts
集成 Electron
1. 安装 Electron 依赖项
- 在项目目录中,安装 Electron 依赖项:
npm install electron
2. 创建主进程文件
- 在
src
目录下创建main.ts
文件:
import { app, BrowserWindow } from 'electron';
const createWindow = () => {
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
},
});
mainWindow.loadFile('index.html');
};
app.whenReady().then(createWindow);
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});
3. 配置 Vite
- 在
vite.config.ts
文件中添加以下内容:
import { defineConfig } from 'vite';
import { createPlugin } from 'vite-plugin-electron-builder';
import vue from '@vitejs/plugin-vue';
// Vite 插件配置
const plugin = createPlugin({
mainProcessFile: 'src/main.ts',
nodeIntegration: true,
});
// Vite 配置
export default defineConfig({
plugins: [vue(), plugin],
});
构建应用
1. 开发模式
- 启动开发模式:
vite build
2. 打包应用
- 打包为可执行文件:
vite build --electron --config electron.config.ts
结论
我们已经成功地从头开始构建了一个基于 Vite 2 + Vue 3 + Electron 的桌面应用。这种技术栈的结合使我们能够高效地创建跨平台的、用户友好的应用程序。
借助 Vite 的闪电般的构建速度和 Electron 的强大功能,我们可以快速迭代并提供卓越的用户体验。随着技术的不断发展,探索这些工具的更多可能性,释放您应用的全部潜力。