Skip to content

electron vite 如何配置 vue 打包多入口

要在 Electron 项目中使用 Vite 配置 Vue 的多入口打包,你可以按照以下步骤操作:

1. 项目结构

确保你的项目结构清晰,例如:

/src
  /main  // Electron 主进程代码
  /renderer
    /entry1 // 第一个 Vue 应用入口
    /entry2 // 第二个 Vue 应用入口
/vite.config.js

2. 配置 vite.config.js

vite.config.js 中配置多个入口。使用 build.rollupOptions.input 来指定多个入口。

javascript
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { resolve } from "path";

export default defineConfig({
  plugins: [vue()],
  build: {
    rollupOptions: {
      input: {
        entry1: resolve(__dirname, "src/renderer/entry1/index.html"),
        entry2: resolve(__dirname, "src/renderer/entry2/index.html"),
      },
      output: {
        // 这里可以配置输出的文件名等
        entryFileNames: "[name]/[name].js",
        chunkFileNames: "[name]/[name].js",
        assetFileNames: "[name]/[name].[ext]",
      },
    },
  },
});

3. 修改 index.html

为每个入口创建一个 index.html,并引入相应的 Vue 组件文件:

例如在 src/renderer/entry1/index.html:

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

src/renderer/entry2/index.html:

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

4. 配置 Electron 主进程

在 Electron 主进程中加载对应的入口 HTML 文件。

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

function createWindow() {
  const win1 = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, "preload.js"),
    },
  });

  win1.loadFile("dist/entry1/index.html");

  const win2 = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, "preload.js"),
    },
  });

  win2.loadFile("dist/entry2/index.html");
}

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

5. 打包与运行

在完成上述配置后,运行 vite build 将会打包两个入口。Electron 将会根据你在主进程中的配置加载相应的入口文件。

这样,你就完成了 Electron Vite 项目中 Vue 的多入口打包配置。