Search code examples
reactjswebpackvitepdf.jsreact-pdf

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


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.

Solution

  • If you need a URL rather than a worker, my solution was just to import the javascript file from node modules. Vite will handle this

    import WorkerPdfJsUrl from 'pdfjs-dist/build/pdf.worker?url'
    
    <Worker workerUrl={WorkerPdfJsUrl} >
      <div
        style={{
          height: '750px',
          width: '900px',
          marginLeft: 'auto',
          marginRight: 'auto',
        }}
      >
        <Viewer
          theme='light'
          fileUrl={pdfFile}
          plugins={[defaultLayoutPluginInstance]}
        />
      </div>
    </Worker>