01 electron+vue3

01 electron+vue3

创建项目

1
2
3
4
npm create vue@latest
npm install
npm install electron@30.0.0
npm install vite-plugin-electron -D

实例

一个简单的 vue3+electron 融合项目,只和这几个文件相关,ASCII 树如下

1
2
3
4
5
6
├── dist
│ └── index.js
├── electron
│ └── index.js
├── package.json
└── vite.config.js

electron/index. js 是 electron 的入口文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import {
    app,
    BrowserWindow
} from 'electron'
const createMainWindow = function () {
    const win = new BrowserWindow({
        title:"title666",
        width:800,
        height:600,
        webPreferences: {
        }
    })
    win.loadURL(process.env['VITE_DEV_SERVER_URL'])
}
app.whenReady().then(res=>{
    createMainWindow()
})

package.json 配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
{
  "name": "eva",
  "version": "0.0.0",
  "private": true,
  "type": "module",
  //配置了electron项目的入口文件,
  "main": "dist/index.js",//这里选择的vite打包好的目录
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "electron": "^30.0.0",
    "pinia": "^2.3.1",
    "vue": "^3.5.13",
    "vue-router": "^4.5.0"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^5.2.1",
    "vite": "^6.0.11",
    "vite-plugin-electron": "^0.29.0",
    "vite-plugin-vue-devtools": "^7.7.0"
  }
}

vite.config.js vite 的配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'
import electron from 'vite-plugin-electron'
// https://vite.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    vueDevTools(),
    //使用vite-electron插件,在dev的同时启动electron
    electron({
    //入口
      entry: 'electron/index.js',
      vite: {
        build: {
        //vite打包的路径默认为dist-electron
            outDir: './dist'
        }
      }
    })
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    },
  },
})