如何配置Vite生产构建生成的HTML文件名?
配置Vite生产构建修改HTML文件名的方法
Rollup的output配置仅负责JS、CSS等资源的命名,HTML文件由Vite内置的HTML插件生成,因此需要通过以下方式修改:
方法一:使用vite-plugin-html插件
这是最直接的定制方案,插件专门用于处理HTML输出:
- 安装插件
npm install vite-plugin-html --save-dev
- 修改
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
相关产品推荐
相关产品推荐

