Next doesn't transpile new URL(...) dependency
Unanswered
Blue orchard bee posted this in #help-forum
Blue orchard beeOP
It is my understanding that in order to use
While that works fine locally,
Adding
How can I make the build comply with
pdfjs-dist
from a Next application, one has to initialize the worker by hand:// NOTE Use legacy build until Node 22
import { GlobalWorkerOptions } from 'pdfjs-dist/legacy/build/pdf';
const url = new URL('pdfjs-dist/legacy/build/pdf.worker.min.mjs', import.meta.url);
GlobalWorkerOptions.workerSrc = url.toString();
While that works fine locally,
next build
will error on that .mjs
file with:static/media/pdf.worker.0dfedf1d.mjs from Terser
x 'import', and 'export' cannot be used outside of module code
,-[90897:1]
90897 | const pdfjsVersion = "4.6.82";
90898 | const pdfjsBuild = "9b541910f";
90899 | var __webpack_exports__WorkerMessageHandler = __webpack_exports__.WorkerMessageHandler;
90900 | export { __webpack_exports__WorkerMessageHandler as WorkerMessageHandler }; //# sourceMappingURL=pdf.worker.mjs.map
: ^^^^^^
`----
Caused by:
0: failed to parse input file
1: Syntax Error
Error:
x 'import', and 'export' cannot be used outside of module code
,-[90897:1]
90897 | const pdfjsVersion = "4.6.82";
90898 | const pdfjsBuild = "9b541910f";
90899 | var __webpack_exports__WorkerMessageHandler = __webpack_exports__.WorkerMessageHandler;
90900 | export { __webpack_exports__WorkerMessageHandler as WorkerMessageHandler }; //# sourceMappingURL=pdf.worker.mjs.map
: ^^^^^^
`----
Adding
pdfjs-dist
to transpilePackages
doesn't seem to have any effect, I'm guessing because I'm not using require
/import
How can I make the build comply with
pdfjs-dist
as MJS since this is what the library provides?3 Replies
West Siberian Laika
@Blue orchard bee
We're you able to get this working? Im trying to get pdf to a png working server side nextjs and getting the same and a couple of problems.
Blue orchard beeOP
Yes but not as well as I would have liked -- see the comments -- since I couldn't use Node 22 for my specific project
Here is what you're (probably) looking for
Here is the specific file where I used those versions https://github.com/angrybacon/vntlnk/blob/master/modules/PoisonDartFrog/read.ts
Here is what you're (probably) looking for
read.ts
import {
getDocument,
GlobalWorkerOptions,
version,
type PDFPageProxy,
// NOTE Use legacy build until Node 22
} from 'pdfjs-dist/legacy/build/pdf';
// NOTE Until I figure out how to make Next transpile the dependency directly,
// we're stuck with Unpkg.
GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${version}/build/pdf.worker.min.mjs`;
package.json
{
"engines": {
"node": ">=20.17.0"
},
"dependencies": {
"pdfjs-dist": "4.6.82",
"tesseract.js": "5.1.1"
},
"devDependencies": {
"typescript": "5.6.2"
}
}
Here is the specific file where I used those versions https://github.com/angrybacon/vntlnk/blob/master/modules/PoisonDartFrog/read.ts