wojtekmaj / react-pdf

Display PDFs in your React app as easily as if they were images.
https://projects.wojtekmaj.pl/react-pdf
MIT License
9.24k stars 877 forks source link

Error since updating from version 7.2.0 to 7.3.0 in next js app #1578

Closed wojtekmaj closed 1 year ago

wojtekmaj commented 1 year ago

Discussed in https://github.com/wojtekmaj/react-pdf/discussions/1577

Originally posted by **benzler** July 31, 2023 Since upgrading to the newest version I have the following error in my typescript next js app: ``` SyntaxError: Named export 'PDFDataRangeTransport' not found. The requested module 'pdfjs-dist' is a CommonJS module, which may not support all module.exports as named exports. ``` This is my code to show the pdf: ``` import { Document, Page, pdfjs } from 'react-pdf'; import 'react-pdf/dist/esm/Page/AnnotationLayer.css'; import 'react-pdf/dist/esm/Page/TextLayer.css'; useEffect(() => { if (typeof window !== 'undefined') { // https://stackoverflow.com/questions/65740268/create-react-app-how-to-copy-pdf-worker-js-file-from-pdfjs-dist-build-to-your pdfjs.GlobalWorkerOptions.workerSrc = new URL( 'pdfjs-dist/build/pdf.worker.min.js', import.meta.url, ).toString(); } }, []); const [numPages, setNumPages] = useState(null); const [pageNumber, setPageNumber] = useState(1); function onDocumentLoadSuccess({ numPages }: { numPages: number }) { setNumPages(numPages); } ``` Can please someone help me how to fix this error? Before updating the code worked perfectly. Seems like I'm not the only one having this issue: https://stackoverflow.com/questions/76796240/named-export-pdfdatarangetransport-not-found-while-using-react-pdf-in-next-js?newreg=704b67926da2412d96aa0144a5a69bd6
wojtekmaj commented 1 year ago

@benzler Can you provide a reproducible example? Just tried on a fresh Next.js app with no issues. Can't even figure out where this error is coming from.

tacomanator commented 1 year ago

Not sure if this is useful but I was able to reproduce this error in a project which uses the pages router only, no app router.

Was having same issue so created test project to reproduce but it worked fine in the new project. I couldn't find any obvious reason so I started copying over pieces of the existing project one-by-one, confirming along the way. Finally I had copied over everything and the new project still worked. The only difference was that the test project had an app folder where as the existing project does not use the app router at all. I deleted the app/ folder from the test project, reinstalled node modules, and the error appeared.

My conclusion is that the error appears when using the pages router only, but not when using the pages router in conjunction with the app router.

wojtekmaj commented 1 year ago

Very helpful actually! Let me try this.