简体   繁体   English

你如何将 Javascript 文件从 node_modules 导入到使用 Vite 的反应中?

[英]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.在我的情况下,如何从 node_modules 加载静态资产 pdf.js(来自 node_modules 的构建文件夹),这样我每次更新时都不必设置版本。

I am migrating from Webpack to Vite, so this is how I use it in my webpack project currently.我正在从 Webpack 迁移到 Vite,所以这就是我目前在我的 webpack 项目中使用它的方式。

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

Webpack configuration Webpack 配置

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

Looking for the Vite equivalent寻找 Vite 等价物

My Vite configuration file is no different from the stock one.我的 Vite 配置文件与库存文件没有什么不同。

Things I tried:我尝试过的事情:

  • I looked at doing a service worker, but that seems more complex than what I'm looking for.我看着做一个服务工作者,但这似乎比我正在寻找的更复杂。

You can import a script as a Web Worker by appending ?worker to the import path:您可以通过将?worker附加到导入路径来将脚本作为 Web Worker 导入:

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

No config is needed.不需要配置。

If you need a URL rather than a worker, my solution was just to import the javascript file from node modules.如果您需要 URL 而不是工作人员,我的解决方案就是从节点模块导入 javascript 文件。 Vite will handle this Vite会处理这个

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM