如何配置Vite使每个入口打包为包含所有依赖的独立单文件
The issue you're hitting is that Rollup (Vite's underlying bundler) automatically extracts shared dependencies like React's JSX runtime into separate chunks to optimize for code reuse. But since you need each Chrome extension entry (popup, background, content script) to be completely self-contained, we need to disable this chunk-splitting behavior.
Here's how to adjust your Vite config to get fully standalone entry files:
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; import path from 'path'; // Keep your existing helper functions (getLastElement, firstUpperCase) here export default defineConfig({ plugins: [ react() ], build: { rollupOptions: { input: { popup: path.resolve(pagesDirectory, 'popup', 'index.html'), background: path.resolve(pagesDirectory, 'background', 'index.ts'), content_script: path.resolve(pagesDirectory, 'content_script', 'ContentScript.tsx') }, // Disable shared chunk splitting entirely manualChunks: () => undefined, output: { entryFileNames: 'src/pages/[name]/index.js', chunkFileNames: isDevelopment ? 'assets/js/[name].js' : 'assets/js/[name].[hash].js', assetFileNames: (assetInfo) => { const { dir, name: _name } = path.parse(assetInfo.name); const assetFolder = getLastElement(dir.split('/')); const name = assetFolder + firstUpperCase(_name); return `assets/[ext]/${name}.chunk.[ext]`; }, // Inline any dynamic imports to keep files self-contained inlineDynamicImports: true } } } })
Key Changes Explained:
manualChunks: () => undefined: This tells Rollup not to create any shared chunks. Every dependency—including React, JSX runtime, and your local components likeBadge—will be bundled directly into its corresponding entry file. No more external imports like../../../assets/jsx-dev-runtime.a077470a.jswill appear in your output.inlineDynamicImports: true: If your code ever uses dynamic imports (not present in your provided content script example), this ensures those imports are inlined into the entry file instead of being split into separate chunks. It’s a safe addition to enforce full standalone behavior.
What to Expect After Rebuilding:
Each entry file (popup/index.js, background/index.js, content_script/index.js) will now be fully self-contained. You can confirm this by checking content_script/index.js—all React-related code and your component logic will be included directly, with no external module imports.
Note that this will increase the file size of each entry, but that’s a necessary tradeoff for having isolated, standalone files that work seamlessly in Chrome extension contexts.
内容的提问来源于stack exchange,提问作者ridermansb

