As mentioned in the
Setting up the worker section, the worker version has to be the same as the version of the
`pdfjs-dist`
package.
Otherwise, you you will see the error message like this:
The API version "2.6.347" does not match the Worker version "2.1.266"
Where `2.6.347`
is the version of `pdfjs-dist`
that you can see in the `package.json`
file:
{
"dependencies": {
"pdfjs-dist": "^2.6.347",
...
}
}
And `2.1.266`
is the version of Worker which is passed to the `Worker`
component as
<Worker workerUrl="https://unpkg.com/pdfjs-dist@2.1.266/build/pdf.worker.min.js">...</Worker>
It isn't convenient and error prone when you upgrade `pdfjs-dist`
but forget to set the same version for the worker.
This post demonstrates some common ways that use the
Webpack bundler to compile and set up the worker source based on the current installed
`pdfjs-dist`
package.
1. Use the worker-loader
Install worker-loader
$ npm install --save-dev worker-loader
Set the pdfjs-dist path
Ask Webpack to load `pdfjs-dist/webpack`
when it sees `pdfjs-dist`
import. Change your Webpack configuration as following:
const path = require('path');
const webpack = require('webpack');
module.exports = {
plugins: [
new webpack.NormalModuleReplacementPlugin(
/^pdfjs-dist$/,
resource => {
resource.request = path.join(__dirname, './node_modules/pdfjs-dist/webpack');
},
),
...
],
};
Build pdfjs worker
const path = require('path');
module.exports = {
entry: {
main: './src/index.tsx',
'pdf.worker': path.join(__dirname, './node_modules/pdfjs-dist/build/pdf.worker.min.js'),
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].bundle.js'
},
...
};
Webpack will build a worker named `pdf.worker.bundle.js`
located in the `dist`
directory.
Set the worker source
Finally, you can set the worker source to the file compiled in the previous section:
import { Worker } from '@react-pdf-viewer/core';
<Worker workerUrl="/pdf.worker.bundle.js">...</Worker>;
2. Use copy-webpack-plugin
Install copy-webpack-plugin
$ npm install --save-dev copy-webpack-plugin
Update webpack config
Change your Webpack configuration as following:
const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
plugins: [
new CopyWebpackPlugin({
patterns: [
{
from: path.join(__dirname, './node_modules/pdfjs-dist/build/pdf.worker.min.js'),
to: path.join(__dirname, 'dist'),
},
],
}),
...
],
};
Webpack will copy the worker file (`pdf.worker.min.js`
) to the `dist`
directory.
Set the worker source
import { Worker } from '@react-pdf-viewer/core';
<Worker workerUrl="/pdf.worker.min.js">...</Worker>;
See also