How to give proper path to public/pdf.worker.js in the file located in src folder.
I am working react-pdf, I have created pdf.worker.js inside public folder, I need to give path to it in one of the component inside src folder. like below
<Document
file={pdf}
options={{ workerSrc: "/pdf.worker.js" }}
onLoadSuccess={onDocumentLoadSuccess}
></Document>
But the thing is I have configured jsconfig.json as below
{
"compilerOptions": {
"baseUrl": "src"
}
}
I am thinking the path to pdf.worker.js is not right and it is not locating the file/loading the file
I have tried inside the component where I am using Document which is working fine
import { Document, Page, pdfjs } from "react-pdf";
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;
but i need to load public/pdf.worker.js instead of doing it inside the component
add in the index.html to make the file known
<head>
<script src="%PUBLIC_URL%/pdf.worker.js"></script>
make a script that copys the pdf.worker.js to your public folder
import path from 'node:path';
import fs from 'node:fs';
const pdfjsDistPath = path.dirname(import.meta.resolve('pdfjs-dist/package.json'));
const pdfWorkerPath = path.join(pdfjsDistPath, 'build', 'pdf.worker.js');
fs.copyFileSync(pdfWorkerPath.substring(5), 'public/pdf.worker.js');
execute in package.json
"build": "node copy_pdf_worker.mjs && react-scripts build",
Needs Node 20. then you neither need pdfjs.GlobalWorkerOptions.workerSrc = ... nor options={{ workerSrc: "/pdf.worker.js" }}. also nothing in the jsconfig.json
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With