Published on

用Electron+vite+vue3搭建桌面端项目

Authors
  • Name
    Twitter

本指南将帮助您使用Electron、Vite和Vue 3搭建一个桌面端应用项目。这个技术栈组合可以让您快速开发出现代化的跨平台桌面应用。

前置条件

确保您的系统已安装Node.js和npm。

步骤

1. 创建项目

创建一个新的项目目录并初始化:

mkdir electron-vite-vue3-app
cd electron-vite-vue3-app
npm init -y

2. 安装依赖

安装必要的依赖:

npm install electron electron-builder vite vue@next @vitejs/plugin-vue
npm install -D concurrently wait-on

3. 创建项目结构

在项目根目录创建以下文件结构:

electron-vite-vue3-app/
├── src/
│   ├── main/
│   │   └── index.js
│   └── renderer/
│       ├── App.vue
│       └── main.js
├── index.html
├── package.json
└── vite.config.js

4. 配置 package.json

编辑 package.json,添加以下脚本:

"scripts": {
  "dev": "concurrently \"vite\" \"electron .\"",
  "build": "vite build && electron-builder"
}

5. 配置 Vite

创建 vite.config.js 文件:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  base: './',
})

6. 配置 Electron 主进程

编辑 src/main/index.js 文件:

const { app, BrowserWindow } = require('electron')
const path = require('path')

function createWindow () {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    }
  })

  if (process.env.NODE_ENV !== 'production') {
    win.loadURL('http://localhost:3000')
  } else {
    win.loadFile('dist/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()
  }
})

7. 配置 Vue 入口文件

编辑 src/renderer/main.js 文件:

import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')

8. 创建 Vue 组件

创建 src/renderer/App.vue 文件:

<template>
  <div>
    <h1>{{ message }}</h1>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: 'Hello Electron + Vite + Vue 3!'
    }
  }
}
</script>

9. 配置 HTML 入口文件

编辑项目根目录下的 index.html 文件:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Electron + Vite + Vue 3 App</title>
</head>
<body>
  <div id="app"></div>
  <script type="module" src="/src/renderer/main.js"></script>
</body>
</html>

运行和构建

开发模式

使用以下命令启动开发服务器:

npm run dev

这将同时启动Vite开发服务器和Electron应用。

构建生产版本

要构建生产版本,运行:

npm run build