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

项目环境

// 1. npm ls vite
├─┬ @vitejs/plugin-vue-jsx@3.1.0
│ └── vite@5.0.3 deduped
├─┬ @vitejs/plugin-vue@4.5.0
│ └── vite@5.0.3 deduped
├─┬ vite-plugin-pwa@0.17.2
│ └── vite@5.0.3 deduped
├─┬ vite-plugin-top-level-await@1.4.0
│ └── vite@5.0.3 deduped
└── vite@5.0.3

// 2.npm ls pdfjs-dist
└── pdfjs-dist@4.0.269

// 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';
posted @ 2023-12-14 10:22  ziChin  阅读(2505)  评论(0编辑  收藏  举报