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

如何配置Vite生产构建生成的HTML文件名?

配置Vite生产构建修改HTML文件名的方法

Rollup的output配置仅负责JS、CSS等资源的命名,HTML文件由Vite内置的HTML插件生成,因此需要通过以下方式修改:

方法一:使用vite-plugin-html插件

这是最直接的定制方案,插件专门用于处理HTML输出:

  1. 安装插件
npm install vite-plugin-html --save-dev
  1. 修改vite.config.js配置:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { createHtmlPlugin } from 'vite-plugin-html'

export default defineConfig({
  plugins: [
    vue(),
    createHtmlPlugin({
      minify: true,
      inject: {},
      // 指定输出的HTML文件名
      filename: 'home.html'
    })
  ],
  build: {
    outDir: 'dist',
    assetsDir: '.',
    rollupOptions: {
      input: 'src/main.js',
      output: {
        entryFileNames: 'home.[hash].js',
        chunkFileNames: 'home.[hash].js',
        assetFileNames: 'home.[hash].[ext]',
      },
    },
  },
})

方法二:自定义构建钩子(无需额外插件)

如果不想安装插件,可利用Vite的writeBundle钩子,在构建完成后重命名HTML文件:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import fs from 'fs'
import path from 'path'

export default defineConfig({
  plugins: [
    vue(),
    {
      name: 'rename-html',
      writeBundle(options, bundle) {
        // 原HTML文件名默认是index.html
        const originalPath = path.join(options.dir, 'index.html')
        // 目标文件名
        const targetPath = path.join(options.dir, 'home.html')
        if (fs.existsSync(originalPath)) {
          fs.renameSync(originalPath, targetPath)
        }
      }
    }
  ],
  build: {
    outDir: 'dist',
    assetsDir: '.',
    rollupOptions: {
      input: 'src/main.js',
      output: {
        entryFileNames: 'home.[hash].js',
        chunkFileNames: 'home.[hash].js',
        assetFileNames: 'home.[hash].[ext]',
      },
    },
  },
})

注意:第二种方法依赖Node内置的fs和path模块,构建完成后会自动将dist/index.html重命名为目标文件名。

内容的提问来源于stack exchange,提问作者blu10

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 17:08:22