如何让Vite将依赖代码内联到Bundle中而非生成单独导入文件?
解决Vite打包Chrome扩展时共享依赖内联问题
我用TypeScript+React开发Chrome扩展,通过Vite打包成background.js、contentScript.js和popup.js三个文件到dist目录,配置的入口如下:
input: { popup: resolve(__dirname, 'src/popup/Popup.tsx'), background: resolve(__dirname, 'src/background/background.ts'), contentScript: resolve(__dirname,'src/contentScript/contentScript.ts'), }
其中chromeStorage.ts同时被contentScript和popup引用,Vite会把它优化成dist下的chromeStorage.js,并在两个bundle里通过import from './chromeStorage.js'引入,但我需要把这段依赖代码直接内联到引用它的文件里。之前试过optimizeDeps.exclude和修改build.rollupOptions.output.format为system都没效果。
解决方案:配置Rollup的manualChunks控制chunk拆分
核心思路是通过Rollup的manualChunks函数,指定chromeStorage.ts不生成独立chunk,而是直接内联到引用它的入口bundle中。修改你的Vite配置如下:
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; import { resolve } from 'path'; export default defineConfig({ plugins: [react()], build: { rollupOptions: { input: { popup: resolve(__dirname, 'src/popup/Popup.tsx'), background: resolve(__dirname, 'src/background/background.ts'), contentScript: resolve(__dirname,'src/contentScript/contentScript.ts'), }, output: { // 自定义chunk拆分规则 manualChunks: (id) => { // 匹配chromeStorage.ts模块,返回undefined表示不生成独立chunk,直接内联 if (id.includes('chromeStorage.ts')) { return undefined; } // 其他node_modules依赖可以继续打包成vendor chunk(可选,根据需求调整) if (id.includes('node_modules')) { return 'vendor'; } } } }, // 可选:如果你的扩展没有其他需要拆分的大依赖,也可以直接禁用代码分割 // rollupOptions: { // output: { // manualChunks: undefined // } // } } });
为什么之前的方法无效?
optimizeDeps.exclude只是阻止Vite预构建该依赖,但Rollup在打包阶段仍会把它识别为共享依赖并拆分出独立chunk;- 修改
output.format为system只是改变模块系统格式,不会影响Rollup的chunk拆分逻辑。
验证效果
重新执行vite build后,检查dist目录下的contentScript.js和popup.js,你会发现chromeStorage.ts的代码已经直接内联到这两个文件中,不会再生成单独的chromeStorage.js,也不会有对它的import语句。
内容的提问来源于stack exchange,提问作者Kami
相关产品推荐
相关产品推荐

