Vite + Electron - 构建桌面应用

使用vue3和vite创建vue的项目然后引入electron

创建Vite项目

    npm create vite@latest electron-desktop-tool

进入到项目 执行安装和运行命令,可以看到vue项目已经启动起来了

cd electron-desktop-tool
npm install
npm run dev

项目可以在浏览器中跑起来,说明没毛病,下一步就在项目中引入 electron

引入electron 到项目中

npm install -D electron electron-builder electron-devtools-installer
vite-plugin-electron

创建项目入口——主进程

electron引入成功了,可以开始写electron的相关代码了,新建一个src-electron 文件用来写electron的代码,在它下面创建一个 main.js文件 用来写主进程代码

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

process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true';

const createWindow = () => {
    const mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            preload: path.join(__dirname, 'preload.js')
        },
    });
    mainWindow.loadURL("http://localhost:3000")
}

app.whenReady().then(() => {
    createWindow();

    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) {
            createWindow();
        }
    });

    app.on('window-all-closed', () => {
        if (process.platform !== 'darwin') {
            app.quit();
        }
    })
})

配置插件入口

配置:vite-plugin-electron

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

// https://vitejs.dev/config/
export default defineConfig({
    plugins: [
        vue(),
        electron({
            // 主进程入口文件
            entry: './src-electron/main.js'
        })
    ],
    /*开发服务器选项*/
    server: {
        // 端口
        port: 3000,
    }
})

配置package.json

在package.json把"type": "module", 删除掉并且配置main字段

// main字段配置为 electron主进程文件路径
"main": "./src-electron/main.js",

electron 启动

运行 npm run dev 启动项目

VSCode中配置运行项

  1. 现在package.json中配置scripts
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview",
    "electron:serve": "vite --host",
    "electron:build": "vite build && electron-builder"
  }
  1. 配置Vscode项目的launcher.json
{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "skipFiles": [
                "<node_internals>/**"
            ],
            "runtimeExecutable": "npm",
            "runtimeArgs": ["run", "electron:serve"],
            "cwd": "${workspaceFolder}"
        }
    ]
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容