Home > other >  How do you import Javascript file from node_modules into react using Vite?
How do you import Javascript file from node_modules into react using Vite?

Time:03-22

How do you load a static asset from node_modules in my case pdf.js (from the build folder of node_modules) so I don't have to set the version every time I update it.

I am migrating from Webpack to Vite, so this is how I use it in my webpack project currently.

<Worker workerUrl="/pdf.worker.bundle.js">

Webpack configuration

'pdf.worker': path.join(__dirname, '../node_modules/pdfjs-dist/build/pdf.worker.js'),

Looking for the Vite equivalent

My Vite configuration file is no different from the stock one.

Things I tried:

  • I looked at doing a service worker, but that seems more complex than what I'm looking for.

CodePudding user response:

You can import a script as a Web Worker by appending ?worker to the import path:

import PdfJsWorker from 'pdfjs-dist/build/pdf.worker.js?worker'
const worker = new PdfJsWorker()                                     
  • Related