vite-plugin-electron: Vite 的 Electron 插件的使用详解

31 min read

Vite 是一个快速的前端构建工具,可以实现近乎于实时的热更新和快速的开发体验。然而,当我们想要将我们的前端应用程序打包为 Electron 应用程序时,我们需要一些额外的配置和插件。vite-plugin-electron 就是一个专门为 Vite 和 Electron 提供的插件,它可以简化我们构建 Electron 应用程序的过程。

下面是使用 vite-plugin-electron 的详细步骤:

  1. 安装依赖

    首先,我们需要安装 Vite 和 Electron,可以通过以下命令进行安装:

    # 安装 Vite
    npm install -g create-vite
    # 创建一个新的 Vite 项目
    create-vite my-app
    # 进入项目目录
    cd my-app
    # 安装 Electron
    npm install electron --save-dev
    
  2. 安装 vite-plugin-electron

    接下来,我们需要安装 vite-plugin-electron,可以使用以下命令进行安装:

    npm install vite-plugin-electron --save-dev
    
  3. 配置 Vite

    在项目根目录下,创建一个 vite.config.js 文件,并添加以下内容:

    const { defineConfig } = require('vite')
    const electron = require('vite-plugin-electron')
    
    module.exports = defineConfig({
      plugins: [
        // 使用 vite-plugin-electron 插件
        electron(),
      ],
    })
    
  4. 创建主进程文件

    在项目根目录下,创建一个 main.ts 文件,作为 Electron 主进程的入口文件。在该文件中可以添加一些初始化 Electron 应用程序的代码。例如:

    import { app, BrowserWindow } from 'electron'
    
    function createWindow() {
      const win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
          nodeIntegration: true,
        },
      })
    
      win.loadURL('http://localhost:3000')
    }
    
    app.on('ready', createWindow)
    
  5. 修改 package.json

    package.json 文件中,添加以下内容:

    {
      "scripts": {
        "start": "vite",
        "build": "vite build",
        "electron:start": "electron .",
        "electron:build": "vite build && electron ."
      }
    }
    

    这里定义了几个 npm script,用于启动开发服务器、构建前端应用程序、启动 Electron 应用程序。

  6. 启动开发服务器

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

    npm run start
    

    它将会在 http://localhost:3000 上启动一个开发服务器,你可以在浏览器中访问该地址来访问你的前端应用程序。

  7. 启动 Electron 应用程序

    使用以下命令启动 Electron 应用程序:

    npm run electron:start
    

    它将会启动 Electron 应用程序,并自动打开你的前端应用程序。

  8. 构建 Electron 应用程序

    使用以下命令构建 Electron 应用程序:

    npm run electron:build
    

    它将会构建你的前端应用程序,并将其打包为一个 Electron 应用程序。

这就是使用 vite-plugin-electron 的详细步骤。使用该插件,我们可以轻松地将我们的 Vite 前端应用程序打包为 Electron 应用程序,并享受 Vite 带来的快速开发体验。