Vite构建多HTML页面:现有手动配置可行,求更优批量处理方案
Vite 批量配置多 HTML 页面方案
不用手动逐个指定HTML文件路径,直接用Node.js原生模块自动扫描目录生成配置:
根目录HTML文件批量处理
修改vite.config.js,通过fs模块读取根目录下所有HTML文件,自动生成rollupOptions.input的配置项:
// vite.config.js import { resolve } from "path"; import { defineConfig } from "vite"; import fs from "fs"; // 自动生成HTML入口配置 function getHtmlEntries() { const entries = {}; // 读取根目录下所有文件,筛选出HTML后缀的 const htmlFiles = fs.readdirSync(__dirname).filter(file => file.endsWith(".html")); htmlFiles.forEach(file => { // 以文件名(不含后缀)作为入口键名 const entryKey = file.slice(0, -5); // 去掉.html后缀 entries[entryKey] = resolve(__dirname, file); }); return entries; } export default defineConfig({ build: { rollupOptions: { input: getHtmlEntries(), }, }, });
子目录HTML文件批量处理
如果HTML文件都放在pages这类子目录下,只需调整扫描路径即可:
function getHtmlEntries() { const entries = {}; const pagesDir = resolve(__dirname, "pages"); const htmlFiles = fs.readdirSync(pagesDir).filter(file => file.endsWith(".html")); htmlFiles.forEach(file => { const entryKey = file.slice(0, -5); entries[entryKey] = resolve(pagesDir, file); }); return entries; }
注意事项
- 确保Node.js版本支持
fs.readdirSync(几乎所有现代Node版本都支持) - 如果需要排除特定HTML文件,可在
filter方法里增加判断,比如file !== "ignore.html"
内容的提问来源于stack exchange,提问作者Dale Wemyss
相关产品推荐
相关产品推荐

