Vite + React项目中保留默认构建及自动生成index.html的同时添加独立入口脚本的方法
Vite + React项目中保留默认构建及自动生成index.html的同时添加独立入口脚本的方法
我完全懂你的困扰——之前Vite会自动生成带React脚本引用的index.html,结果加了多入口配置后这个关键的HTML文件直接消失了。这其实是因为手动指定Rollup的input为TS文件时,Vite会切换到纯Rollup的多入口模式,不再默认处理HTML入口的解析和生成逻辑了。下面给你两种靠谱的解决方案,既能保留原有React应用的完整构建流程,又能顺利打包你的独立脚本:
方案一:将HTML文件加入Rollup入口(推荐)
Vite默认是靠项目根目录的index.html来启动构建并生成最终的dist/index.html的——你可能之前没太留意这个文件,毕竟React模板默认就带了它。所以我们只要把这个HTML文件也加入Rollup的input配置里,就能让Vite继续处理它,同时打包你的独立脚本。
修改后的Vite配置如下:
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react-swc'; import { resolve } from 'path'; export default defineConfig({ plugins: [react()], build: { rollupOptions: { input: { // 加入Vite默认的HTML入口,确保index.html被正常生成 app: resolve(__dirname, 'index.html'), // 你的独立脚本入口 myOtherScript: resolve(__dirname, 'src/my-other-script.ts'), }, output: { entryFileNames: (chunkInfo) => { // 给独立脚本指定固定的输出文件名,不带哈希 if (chunkInfo.name === 'myOtherScript') { return 'my-other-script.js'; } // React应用的脚本和chunk保持原有哈希命名规则,避免缓存问题 return 'assets/[name].[hash].js'; }, chunkFileNames: 'assets/[name].[hash].js', assetFileNames: 'assets/[name].[hash][extname]', }, }, }, });
配置说明:
input.app指向项目入口HTML文件,Vite会继续解析这个文件,自动注入React打包后的脚本和CSS引用,最终生成dist/index.html。input.myOtherScript指向你的独立脚本入口,通过entryFileNames的条件判断,让它输出为固定名称的dist/my-other-script.js。- 其余的脚本、chunk和资源(如CSS)保持原来的哈希命名规则,避免浏览器缓存旧资源。
方案二:使用自定义Rollup插件单独打包独立脚本
如果你不想修改默认的入口配置,可以添加一个自定义Rollup插件,在Vite完成React应用构建后,额外打包你的独立脚本:
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react-swc'; import { rollup } from 'rollup'; import typescript from '@rollup/plugin-typescript'; import { resolve } from 'path'; export default defineConfig({ plugins: [ react(), // 自定义插件:在Vite构建完成后额外打包独立脚本 { name: 'build-other-script', async closeBundle() { const bundle = await rollup({ input: resolve(__dirname, 'src/my-other-script.ts'), plugins: [typescript()], }); await bundle.write({ file: resolve(__dirname, 'dist/my-other-script.js'), format: 'es', // 可根据需求改成iife、cjs等格式 }); await bundle.close(); }, }, ], });
配置说明:
- 这个插件会在Vite完成默认的React应用构建后(触发
closeBundle钩子),调用Rollup单独打包my-other-script.ts,输出到dist/my-other-script.js。 - 如果你的脚本是TypeScript编写的,需要先安装
@rollup/plugin-typescript:npm install @rollup/plugin-typescript --save-dev。
两种方案都能生成你需要的输出结构:
dist/assets/index-[hash].js dist/assets/index-[hash].css dist/index.html dist/my-other-script.js
备注:内容来源于stack exchange,提问作者chitzui
相关产品推荐
相关产品推荐

