This issue seems to arise due to esModule option introduced in [email protected].

The fix for this was merged in (pre-release) [email protected]

You can fix this by either upgrading pdfjs-dist to v2.6.347 OR downgrading worker-loader to v2.0.0

Answer from Siddhesh on Stack Overflow
Top answer
1 of 6
14

This issue seems to arise due to esModule option introduced in [email protected].

The fix for this was merged in (pre-release) [email protected]

You can fix this by either upgrading pdfjs-dist to v2.6.347 OR downgrading worker-loader to v2.0.0

2 of 6
7

I just had to solve this issue myself...

This issue

Module not found: Error: Can't resolve 'module' in '/home/giampaolo/dev/KJ_import/KJ-JS/node_modules/webpack/lib/node'

Is caused by worker-loader loading NodeTargetPlugin, which in turn runs require("module") which I think (but I'm not 100%) is for native node modules, which when running Webpack targeted for web is not relevant

This issue can be mitigated with Webpack config

{
  node: {
    module: "empty"
  }
}

Afterwards, things move along farther, but I needed further mitigations:

import pdfjsLib from "pdfjs-dist/webpack";

This runs pdfjs-dist/webpack.js:27 which is

var PdfjsWorker = require("worker-loader!./build/pdf.worker.js");

Which is attempting to load pdf.worker.js (which worker-loader should be packaging) and then tries to instantiate the class:

pdfjs.GlobalWorkerOptions.workerPort = new PdfjsWorker();

The issue I had was that Webpack packaged pdf.worker.js as an esModule (the default for worker-loader), so the way it was require'd needs to be unwrapped with the default property on the imported esModule (said another way, the instantiation would have to be new PdfjsWorker.default()

I was able to mitigate this with the NormalModuleReplacementPlugin plugin, which is able to re-write the require statement based on a regex match/replace, which is matching the original require string and replacing it with one that sets the worker-loader option esModule=false, followed by the absolute path to the pdf.worker.js file on the local system:

new webpack.NormalModuleReplacementPlugin(
  /worker-loader!\.\/build\/pdf\.worker\.js$/,
  "worker-loader?esModule=false!" + path.join(__dirname, "../", "node_modules", "pdfjs-dist", "build", "pdf.worker.js")
)

It's important to match the complete original require string of /worker-loader!\.\/build\/pdf\.worker\.js$/ and not just the pdf.worker.js part, because you could end up in an infinite replace loop.

You need to fix the replacement string to be a proper path for your project, which would probably be

"worker-loader?esModule=false!" + path.join(__dirname, "node_modules", "pdfjs-dist", "build", "pdf.worker.js")

I have a ../ in my path because this code is being executed inside storybooks .storybook/ folder, so I have go up a directory to get to node_modules/

And with those two changes, everything for PDF.js seems to be working.

And lastly, if you want to ignore the warnings about the missing FetchCompileWasmPlugin and FetchCompileAsyncWasmPlugin modules, you can setup the webpack IgnorePlugin to just ignore these imports, my assumption is they're WASM based and not actually needed

plugins: [
  new webpack.IgnorePlugin({ resourceRegExp: /FetchCompileWasmPlugin$/ }),
  new webpack.IgnorePlugin({ resourceRegExp: /FetchCompileAsyncWasmPlugin$/ })
]

I'm guessing there might be some out-of-date mismatch of worker-loader and the modules in the currently installed Webpack version, but these WASM modules don't seem to be necessary for our purposes

🌐
npm
npmjs.com › package › pdfjs-dist
pdfjs-dist - npm
npm i pdfjs-dist · github.com/mozilla/pdf.js · mozilla.github.io/pdf.js/ 6,183,977 · 5.4.449 · Apache-2.0 · 37.2 MB · 388 · 12 days ago · yurydelendik · pdfjsbot · brendandahl · calixteman · pdfjs-release-automation · Try on RunKit ·
      » npm install pdfjs-dist
    
Published   Nov 29, 2025
Version   5.4.449
🌐
GitHub
github.com › mozilla › pdf.js › issues › 15302
Correct way to use pdf.js with NPM/Yarn and Webpack 5 · Issue #15302 · mozilla/pdf.js
June 4, 2022 - GlobalWorkerOptions.workerPort = new Worker(new URL('pdfjs-dist/build/pdf.worker', import.meta.url)); This follows webpack's documentation on how to use web workers ·
Published   Aug 11, 2022
🌐
GitHub
github.com › mozilla › pdf.js › wiki › setup-pdf.js-in-a-website
Setup PDF.js in a website
The worker shall be built into ... PDFJS.workerSrc shall be set to point to this file. You can use the pdfjs-dist/webpack module for PDF.js autoconfiguration....
Author   mozilla
🌐
GitHub
github.com › mozilla › pdfjs-dist › blob › master › webpack.js
pdfjs-dist/webpack.js at master · mozilla/pdfjs-dist
Generic build of PDF.js library. . Contribute to mozilla/pdfjs-dist development by creating an account on GitHub.
Author   mozilla
🌐
Ember.JS
discuss.emberjs.com › questions › build issues
(pdf.js) Build Error (Bundler) webpack returned errors to ember-auto-import - Build Issues - Ember.JS
December 30, 2022 - Hi there, I’ve been trying to import the PDF.js library and by extenstion pdfjs-dist into my ember app however I receive this error: ERROR in ./node_modules/pdfjs-dist/build/pdf.js 1361:17 Module parse failed: Unexpected character '#' (1361:17) File was processed with these loaders: * ./node_modules/babel-loader/lib/index.js You may need an additional loader to handle the result of these loaders.
🌐
GitHub
github.com › mozilla › pdf.js › issues › 17319
`import * as pdfjsLib from 'pdfjs-dist/webpack';` needs `.mjs` · Issue #17319 · mozilla/pdf.js
October 11, 2023 - -pdfjsLib.GlobalWorkerOptions.workerSrc = - "../../build/webpack/pdf.worker.bundle.js"; - // Loading a document. const loadingTask = pdfjsLib.getDocument(pdfPath); const pdfDocument = await loadingTask.promise; diff --git a/examples/webpack/webpack.config.js b/examples/webpack/webpack.config.js index 47301843c..b5c049340 100644 --- a/examples/webpack/webpack.config.js +++ b/examples/webpack/webpack.config.js @@ -6,8 +6,7 @@ const path = require("path"); module.exports = { context: __dirname, entry: { - main: "./main.mjs", - "pdf.worker": "pdfjs-dist/build/pdf.worker.mjs", + main: "./main.mjs" }, mode: "none", output: {
Published   Nov 22, 2023
🌐
GitHub
github.com › mozilla › pdf.js › issues › 10940
Document pdfjs-dist/webpack · Issue #10940 · mozilla/pdf.js
March 28, 2019 - Document pdfjs-dist/webpack#10940 · #11081 · Copy link · Labels · other · maclockard · opened · on Jul 2, 2019 · Issue body actions · The current webpack example makes no mention of this as an option or how to correctly use it with worker loader. Instead, I only found it by looking at this comment: #7612 (comment) 👍React with 👍5bryanph, agilgur5, Joozty, bobotangpy and Jakedalus ·
Published   Jul 02, 2019
Find elsewhere
🌐
GitHub
github.com › mozilla › pdf.js › issues › 8647
Using pdfjs-dist/webpack results in pdf.worker.js imported twice · Issue #8647 · mozilla/pdf.js
February 6, 2017 - I've analyzed the result using webpack JSON stats. From that I realized that pdf.worker.js is imported twice. One is 8d94cec765cddcb66c2d.worker.js file. This is the one that is correctly loaded and used. What you can see though is a second, 0.bundle.js file. This bundle contains a second copy of pdf.worker.js, as pdfjs-dist/build/pdf.js requests for it, but this time without 'worker-loader!' prefix.
Published   Jul 13, 2017
🌐
Stack Overflow
stackoverflow.com › questions › tagged › pdfjs-dist
Highest scored 'pdfjs-dist' questions - Stack Overflow
Trying to use pdfjs-dist in node js app Steps: created new node js app (module) then:- npm i pdfjs-dist package.json is:- "name": "testpdf", "version": "1.0.0&...
🌐
PDF.js Express
pdfjs.express › documentation › get-started › npm
Integrating PDF.js Express Plus with NPM | Documentation
then add the following to your webpack config: module.exports = { ...otherConfig, plugins: [ new CopyPlugin([{ from: './node_modules/@pdftron/pdfjs-express/public', to: './dist/public/pdfjsexpress' }] ), ], }; Parcel · If you are using parcel to bundle your project, you can use parcel-plugin-static-files-copy to copy your files.
🌐
GitHub
github.com › mozilla › pdf.js › issues › 10838
Webpack should handle loading worker instead of setting workerSrc · Issue #10838 · mozilla/pdf.js
February 13, 2019 - When following the Webpack example and importing pdfjs-dist with import * as pdfjsLib from 'pdfjs-dist'; Webpack will create a pdfjsWorker.js and also automatically load it in the browser. The file may be named differently(hashed names, ...
Published   May 20, 2019
🌐
UNPKG
unpkg.com › browse › [email protected] › webpack.mjs
pdfjs-dist/webpack.mjs
Version: 1.0.8131.0.8161.0.8181.0.8201.0.8221.0.8241.0.8261.0.8281.0.8301.0.8331.0.8351.0.8371.0.8491.0.8511.0.8531.0.8551.0.8581.0.8611.0.8631.0.8641.0.8671.0.8691.0.8721.0.8741.0.8761.0.8781.0.8801.0.8821.0.8841.0.8871.0.8891.0.8921.0.8941.0.8961.0.8981.0.9001.0.9031.0.9051.0.9071.0.9091...
Top answer
1 of 6
9

Here's a super ugly workaround for client-components, until something better is proposed (I hate this too, but it works):

npm i pdfjs-dist

Edit 1: A hook might be better for reusability:

Create Your Hook

"use client";
import {useEffect} from "react";
import * as PDFJS from "pdfjs-dist/types/src/pdf";

export const usePDFJS = (onLoad: (pdfjs: typeof PDFJS) => Promise<void>, deps: (string | number | boolean | undefined | null)[] = []) => {
  
  const [pdfjs, setPDFJS] = useState<typeof PDFJS>(null);
  
  // load the library once on mount (the webpack import automatically sets-up the worker)
  useEffect(() => {
    import("pdfjs-dist/webpack.mjs").then(setPDFJS)
  }, []);

  // execute the callback function whenever PDFJS loads (or a custom dependency-array updates)
  useEffect(() => {
    if(!pdfjs) return;
    (async () => await onLoad(pdfjs))();
  }, [ pdfjs, ...deps ]);
}

Typescript Fix

Your compiler might complain about a typescript issue; if so, I just added an index.d.ts (note the .d.ts) at the same level as my hook:

declare module 'pdfjs-dist/webpack.mjs' { export * from 'pdfjs-dist' }

Use Your Hook

"use client";
import {usePDFJS} from "...";


export default function Page() {
  usePDFJS(async (pdfjs) => {
    console.log(pdfjs)
  })
}
2 of 6
4

There's a pretty lengthy discussion over on Github issues where people have managed to get it working either on client:

I decided to follow a simple path, I downloaded the stable version from the official website. I put all the files in the public folder. Then I added this tag to my component:

<script src="/pdfjs/pdf.mjs" type="module" />

then adding code in useEffect:

  const pdfjs = window.pdfjsLib as typeof import('pdfjs-dist/types/src/pdf')
  const pdfjsWorker = await import('pdfjs-dist/build/pdf.worker.min.mjs');
  pdfjs.GlobalWorkerOptions.workerSrc = pdfjsWorker;

  const pdfDocument = pdfjs.getDocument('http://localhost:3000/pdf-files/myFile.pdf')

  console.log('pdfDocument', pdfDocument);

Or server-side, via appDir (e.g. app/api/pdf/route.js)

import * as pdfjs from 'pdfjs-dist/build/pdf.min.mjs';
await import('pdfjs-dist/build/pdf.worker.min.mjs');

export async function POST(req, res) {
  const pdf = await pdfjs.getDocument(
    'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf'
  ).promise;
  const page = await pdf.getPage(1);
  const textContent = await page.getTextContent();
  return NextResponse.json({ message: textContent }, { status: 200 });
}

I've personally just tested this last API-one on Next.js 14.1.1 and it works just fine after a npm install pdfjs-dist

🌐
Wix Studio
forum.wixstudio.com › ask the community
How can I use pdfjs-dist with Velo? - Ask the community - Community Support Forum | Wix Studio
December 25, 2020 - I would like to render pdfs that are stored in a document collection. I have installed pdfjs-dist and require. In the following example I make an attempt to call getDocument from the pdfjsLib with a base64 encoded pdf taken from this example. var pdflib = require('pdfjs-dist/build/pdf.js'); pdflib.GlobalWorkerOptions.workerSrc = "pdfjs-dist/build/pdf.worker.js"; var pdfData = atob( 'JVBERi0xLjcKCjEgMCBvYmogICUgZW50cnkgcG9pbnQKPDwKICAvVHlwZSAvQ2F0YWxvZwog' + 'IC9QYWdlcyAyIDAgUgo+PgplbmRvYm...
🌐
npm
npmjs.com › package › embed-pdfjs-dist
embed-pdfjs-dist - npm
Generic build of Mozilla's PDF.js library. An embedded viewer provided.. Latest version: 2.0.89, last published: 8 years ago. Start using embed-pdfjs-dist in your project by running `npm i embed-pdfjs-dist`. There are no other projects in the npm registry using embed-pdfjs-dist.
      » npm install embed-pdfjs-dist
    
Published   Nov 03, 2017
Version   2.0.89