You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何移除Vite.js多HTML入口打包生成的文件夹结构?

Vite打包时将HTML文件输出到dist根目录的解决方案

问题背景

现有Vite项目结构中,HTML文件存放在src/html/目录下,打包后这些文件会被输出到dist/src/html/路径下,但需要将它们直接放在dist根目录,同时保留源码中HTML文件的原有位置。

解决方案

方法1:通过Rollup输出配置直接指定HTML路径

修改vite.config.js中的Rollup输出配置,为HTML入口文件指定根目录的输出路径:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { fileURLToPath } from 'url';

export default defineConfig({
  plugins: [react()],
  build: {
    assetsDir: './',
    rollupOptions: {
      input: {
        main: fileURLToPath(new URL('./src/html/main.html', import.meta.url)),
        mobile: fileURLToPath(new URL('./src/html/mobile.html', import.meta.url)),
        config: fileURLToPath(new URL('./src/html/config.html', import.meta.url)),
      },
      output: {
        dir: 'dist',
        // 为HTML入口文件指定输出到dist根目录
        entryFileNames: '[name].html',
        // 确保JS chunk和其他资源保持带哈希的命名规则,避免缓存问题
        chunkFileNames: '[name]-[hash].js',
        assetFileNames: '[name]-[hash].[ext]'
      },
    },
  },
});

方法2:自定义Vite插件移动打包后的HTML文件

如果Rollup配置的方式不符合需求,可以编写一个简单的插件,在打包完成后将HTML文件从dist/src/html/移动到dist根目录:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { fileURLToPath } from 'url';
import fs from 'fs/promises';
import path from 'path';

const moveHtmlPlugin = () => ({
  name: 'move-html',
  async buildEnd() {
    const distRoot = path.resolve(__dirname, 'dist');
    const srcHtmlDir = path.join(distRoot, 'src/html');
    
    try {
      // 读取目标目录下的所有HTML文件
      const files = await fs.readdir(srcHtmlDir);
      for (const file of files) {
        if (file.endsWith('.html')) {
          await fs.rename(
            path.join(srcHtmlDir, file),
            path.join(distRoot, file)
          );
        }
      }
      // 删除空目录
      await fs.rmdir(srcHtmlDir);
      await fs.rmdir(path.join(distRoot, 'src'));
    } catch (err) {
      console.error('移动HTML文件失败:', err);
    }
  }
});

export default defineConfig({
  plugins: [react(), moveHtmlPlugin()],
  build: {
    assetsDir: './',
    rollupOptions: {
      input: {
        main: fileURLToPath(new URL('./src/html/main.html', import.meta.url)),
        mobile: fileURLToPath(new URL('./src/html/mobile.html', import.meta.url)),
        config: fileURLToPath(new URL('./src/html/config.html', import.meta.url)),
      },
      output: {
        dir: 'dist',
      },
    },
  },
});

方法对比

  • 方法1更高效,直接通过构建配置控制输出路径,无额外文件IO操作;
  • 方法2逻辑更直观,适合需要自定义复杂文件迁移逻辑的场景。

内容的提问来源于stack exchange,提问作者Luis Vinicius M.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 04:50:23