webpack
Set up React PDF Viewer with webpack 5, emitting the PDF.js worker as an asset and extracting the stylesheet.
Before you start
- Tested with webpack 5.111,
css-loader7.1,mini-css-extract-plugin2.9, React 19.3 andpdfjs-dist6.3. The consumer smoke test builds this setup against the packed package on every CI run. - Install the package first: see Installation.
Setup
1. Configure the loaders. The package ships ES modules and a plain CSS file:
// webpack.config.mjs
import MiniCssExtractPlugin from 'mini-css-extract-plugin';
export default {
entry: './src/main.jsx',
output: {
filename: '[name].[contenthash].js',
assetModuleFilename: '[name].[contenthash][ext]',
clean: true,
},
resolve: { extensions: ['.jsx', '.js', '.mjs'] },
module: {
rules: [
// your JSX / TypeScript loader here
{ test: /\.m?js$/, resolve: { fullySpecified: false } },
{ test: /\.css$/, use: [MiniCssExtractPlugin.loader, 'css-loader'] },
],
},
plugins: [new MiniCssExtractPlugin()],
};
2. Configure the worker in your entry module. webpack 5 emits the file referenced by new URL(…, import.meta.url) as an asset:
// src/main.jsx
import { configurePdfJs, PdfViewer } from '@kingtech/react-pdf-viewer';
import '@kingtech/react-pdf-viewer/styles.css';
import { createRoot } from 'react-dom/client';
configurePdfJs({
workerSrc: new URL('pdfjs-dist/build/pdf.worker.min.mjs', import.meta.url).toString(),
});
createRoot(document.getElementById('root')).render(<PdfViewer source="/report.pdf" />);
3. Optional: self-host the other assets with copy-webpack-plugin:
import CopyPlugin from 'copy-webpack-plugin';
new CopyPlugin({
patterns: ['cmaps', 'standard_fonts', 'wasm', 'iccs'].map((dir) => ({
from: `node_modules/pdfjs-dist/${dir}`,
to: `pdfjs/${dir}`,
})),
});
Then pass cMapUrl: '/pdfjs/cmaps/', standardFontDataUrl: '/pdfjs/standard_fonts/', wasmUrl: '/pdfjs/wasm/' and iccUrl: '/pdfjs/iccs/' to configurePdfJs.
Verify
- Run
webpack --mode productionand check thatdist/contains apdf.worker.min.*.mjsfile and a CSS file that includes.rpv-root. - Serve
dist/, open the page and confirm the first page renders and the worker loads from your origin.
Known issues
- “Can’t resolve” errors for extensionless imports inside
pdfjs-dist. Strict ESM resolution rejects them; thefullySpecified: falserule in step 1 fixes it. - Worker served with the wrong MIME type. Serve
.mjsfiles astext/javascript, or the browser refuses to start the worker.