首页 > 其他分享 >import引入pdfjs-dist报错Top-level await is not available、No "GlobalWorkerOptions.workerSrc"等

import引入pdfjs-dist报错Top-level await is not available、No "GlobalWorkerOptions.workerSrc"等

时间:2023-12-14 10:36:19浏览次数:94  
标签:available dist level await pdfjsWorker 报错 pdfjs vite

项目环境

// 1. npm ls vite
├─┬ @vitejs/[email protected]
│ └── [email protected] deduped
├─┬ @vitejs/[email protected]
│ └── [email protected] deduped
├─┬ [email protected]
│ └── [email protected] deduped
├─┬ [email protected]
│ └── [email protected] deduped
└── [email protected]

// 2.npm ls pdfjs-dist
└── [email protected]

// 3.node -v
v18.18.0




  • 报错1:
Top-level await is not available in the configured target environment ("chrome87", "edge88", "es2020", "firefox78", "safari14" + 2 overrides)

    node_modules/pdfjs-dist/build/pdf.mjs:17349:53:
      17349 │ /******/ __webpack_exports__ = globalThis.pdfjsLib = await (globalThis.pdfjsLibPromise = __webpack_exports__);
  • 原因:vite 不支持顶级的 async/await 语法,需要安装插件做兼容
  • 解决方案:
    vite.config.ts 安装并引入 topLevelAwait
npm install vite-plugin-top-level-await -D
// vite.config.ts 文件
// 解决 vite build打包报错Top-level await is not available
import topLevelAwait from 'vite-plugin-top-level-await'

export default ({ mode }: any) => {
    return defineConfig({
        plugins: [
            topLevelAwait({
                promiseExportName: '__tla',
                promiseImportName: (i) => `__tla_${i}`
            })
        ],
    })
}



  • 报错2:
Uncaught (in promise) Error: No "GlobalWorkerOptions.workerSrc" specified.
  • 原因:pdfjs-dist 包需要用到 webWorker 线程做大量的计算,需要全局引入 pdfjsWorker
  • 解决方案:从 pdfjs-dist 导入 pdfjsWorker 并挂载到 window 变量上
import * as pdfjsLib from 'pdfjs-dist'
import * as pdfjsWorker from 'pdfjs-dist/build/pdf.worker.mjs'
(window as any).pdfjsWorker = pdfjsWorker



  • 报错3:
找不到模块“pdfjs-dist/build/pdf.worker.mjs”或其相应的类型声明。ts(2307)
  • 原因:如果是 <script setup lang="ts"> 模块式,引入 pdfjsWorker 需要申明模块

  • 解决方案:创建模块声明文件 并 声明 pdfjsWorker

// env.d.ts
/// <reference types="vite/client" />
declare module 'pdfjs-dist/build/pdf.worker.mjs';

标签:available,dist,level,await,pdfjsWorker,报错,pdfjs,vite
From: https://www.cnblogs.com/ziChin/p/17900591.html

相关文章