I've had problems that many had regarding using pdf.worker.js inside my react application (I build a wrapper on pdf.js for react).
I'm using Create React App, I tried many things from hosting from cloud:
PdfJsLib.GlobalWorkerOptions.workerSrc = PDFJS_WORKER_CLOUD_URL;
this works but I must make it work locally.
trying to use a local path does not work.
I read many issues and posts of stackoverflow, as well as did research but could not come with the right solution.
so my question is in 2019 - what is the recommended way to use pdf.js worker inside create-react-app
I don't think anybody here is a React developer, so we can't help out with that, especially without a running example. There is a working example in https://github.com/mozilla/pdf.js/blob/master/examples/components/pageviewer.js#L25, so if that doesn't work for you then it's most likely something in create-react-app
.
It looks like https://github.com/wojtekmaj/react-pdf/issues/291 is a similar problem.
I have found a workaround for this problem.
First, copy the pdf.worker.min.js to src/ folder and changed the
filename extension to something else than .js, like .data or .txt
cd src/
cp ../node_modules/pdfjs-dist/build/pdf.worker.min.js pdf.worker.min.data
Then, in your javascript files, set the workerSrc like this.
import workerURL from "./pdf.worker.min.data";
pdfjsLib.GlobalWorkerOptions.workerSrc = workerURL;
This will trick the create-react-app to think pdf.worker.min.js as a data file and
put the file in /build/static/media, so pdf.worker.min.js will be cached by the
default service worker configuration.
This way is simple and work with vanilla create-react-app without eject and
is compatible with the default service worker, you can check this file in my
project for an example.
Most helpful comment
I have found a workaround for this problem.
First, copy the pdf.worker.min.js to src/ folder and changed the
filename extension to something else than .js, like .data or .txt
Then, in your javascript files, set the workerSrc like this.
This will trick the create-react-app to think pdf.worker.min.js as a data file and
put the file in /build/static/media, so pdf.worker.min.js will be cached by the
default service worker configuration.
This way is simple and work with vanilla create-react-app without eject and
is compatible with the default service worker, you can check this file in my
project for an example.