How to use the pdf.js library with Vue and vite

July 07, 2022

Shortly after migrating our development tooling at Lob from vue-cli to vite we discovered that our use of the pdf.js library was no longer working.

Importing the pdf.js library used to be as simple as:

import * as pdfjsLib from 'pdfjs-dist/webpack';

But importing from that file requires the use of webpack and vite is built upon rollup. We needed to deconstruct what all was being done in this file and find a non-webpack way to accomplish the same things. We have to import the pdf.worker as a service worker and the way service workers are registered in vite/rollup versus webpack is different. So we needed to use vite’s method for doing that (https://vitejs.dev/guide/features.html#import-with-query-suffixes).

Additionally we ended up needing to use the CDN version to pass as the workerSrc rather than pointing to the pdf.worker.js file bundled with the library in node_modules.

Here’s the final version of the code we ended up using to get pdf.js working with vite:

import * as pdfjs from 'pdfjs-dist/build/pdf'; import pdfjsWorker from 'pdfjs-dist/build/pdf.worker?worker'; import * as Sentry from '@sentry/vue'; const init = () => { try { if (typeof window === 'undefined' || !('Worker' in window)) { throw new Error('Web Workers not supported in this environment.'); } window.pdfjsWorker = pdfjsWorker; pdfjs.GlobalWorkerOptions.workerSrc = `https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`; } catch (error) { Sentry.captureException(`Unable to load pdfjs: ${error}`); } }; export default { install: (app) => { init(); app.config.globalProperties.$pdf = pdfjs; } };