尝试在vite构建中包含多个html页面

问题描述 投票:0回答:1

这工作正常,但是有没有更好的方法来处理所有 html 文件?

// vite.config.js
import { resolve } from "path";
import { defineConfig } from "vite";

export default defineConfig({
  build: {
    rollupOptions: {
      input: {
        main: resolve(__dirname, "index.html"),
        contact: resolve(__dirname, "contact.html"),
        blog: resolve(__dirname, "font-sizes.html"),
      },
    },
  },
});

我尝试过其他关于堆栈溢出的想法,但它们不起作用。

javascript vite rollupjs
1个回答
0
投票

编写一个函数来读取所有 html 文件并返回一个对象,正如 vite 所期望的那样

import path from 'path';
import fs from 'fs';

function getHtmlEntries() {
  const pagesDir = path.resolve(__dirname, "");
  const entries = {};

  // Read all files in the directory
  const files = fs.readdirSync(pagesDir);

  // Filter out HTML files
  const htmlFiles = files.filter((file) => file.endsWith(".html"));

  // Create entries for each HTML file
  htmlFiles.forEach((file) => {
    const name = path.basename(file, ".html");
    entries[name] = path.resolve(pagesDir, file);
  });

  return entries;
}

注意:如果您的 html 文件位于另一个目录中,则在pagesDir变量中输入目录名称,或者将其保留为空:)

就是这样。现在将该函数放入汇总输入配置中。

build: {
    rollupOptions: {
      input: getHtmlEntries()
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.