PDFJS场景下Webpack如何合并0.bundle与主bundle
Let's break down what's happening and how to get a single bundle file as you need:
What's Causing the Extra Bundle
The 0.bundle.js file is being created for two key reasons:
- PDF.js internally includes logic that Webpack identifies as a separate split point—most often related to its worker functionality. Even though you commented out the
pdf.workerentry, importingpdfjs-dist/web/pdf_viewer.jsstill triggers Webpack to split off part of the code (usually the worker runtime) into a separate chunk. - Webpack's default
splitChunksoptimization is designed to separate vendor code (like PDF.js) from your application code to improve caching. This automatic splitting is generating the extra bundle file.
How to Combine Everything into One Bundle
Here are two reliable approaches to get a single main.bundle.js file that works with PDF.js:
1. Disable Automatic Chunk Splitting
Add an optimization section to your Webpack config to turn off Webpack's default chunk splitting behavior:
module.exports = { entry: { 'main': './src/main.ts', }, output: { path: path.join(__dirname, 'dist'), filename: '[name].bundle.js', }, // Add this section to force single bundle optimization: { splitChunks: false, runtimeChunk: false, // Optional: prevents a separate runtime chunk from being generated }, // ... rest of your existing config };
This forces Webpack to bundle all code—your application logic, PDF.js, and its associated worker-related code—into a single main.bundle.js file.
2. Inline the PDF Worker Directly (For Stubborn Cases)
If disabling split chunks doesn't fully resolve the issue (sometimes PDF.js still tries to load a worker dynamically), you can embed the worker code directly into your main bundle:
- First install
worker-loaderto handle worker files:npm install worker-loader --save-dev - Update your Webpack config to process the PDF worker entry:
module.exports = { // ... other config settings module: { rules: [ // ... your existing rules (e.g., ts-loader for TypeScript) { test: /pdf\.worker\.entry\.js$/, use: { loader: 'worker-loader', options: { inline: 'fallback' } } } ] } }; - In your
main.ts, import and assign the inlined worker explicitly:import { PDFJS } from 'pdfjs-dist/web/pdf_viewer.js'; import PdfWorker from 'pdfjs-dist/build/pdf.worker.entry.js'; // Tell PDF.js to use the inlined worker instead of loading it dynamically PDFJS.GlobalWorkerOptions.workerSrc = () => new PdfWorker();
This embeds the worker code directly into your main bundle, eliminating the need for a separate chunk file.
Verify the Fix
After updating your config and code, run your Webpack build again. You should only see main.bundle.js in the dist directory, and your PDF.js functionality should work as expected.
内容的提问来源于stack exchange,提问作者Romain Bruckert

