如何 utilize/resolve 来自动态导入的承诺

How to utilize/resolve a promise from a Dynamic Import

您如何利用/解决 Dynamic Import 中的 promise

下面的想法是仅在需要时导入 jspdf 库。

to_pdf() {
      const filename = `${this.staff.staff_no}.pdf`

      html2canvas(document.getElementById('rpt'), { scale: 4 }).then(c => {
        import('jspdf').then(jsPDF => { // error: Uncaught (in promise) TypeError: jsPDF is not a constructor
          let pdf = new jsPDF({
            orientation: 'p',
            unit: 'mm',
            format: 'a4',
            putOnlyUsedFonts: true,
            compress: true,
            precision: 4
          })
          const hgt = (c.height / c.width) * 200
          pdf.addImage(c.toDataURL('image/jpeg', 1), 'JPEG', 4, 10, 200, hgt)
          pdf.save(filename)
        })
      })
    }

上面的代码给出了这个错误:

Uncaught (in promise) TypeError: jsPDF is not a constructor

因为import()解析为模块(一个对象)。出口是它的财产。 (正如 Wendelin 评论的那样)

您需要了解模块内部的内容是如何导出的。在这种情况下:

import('jspdf').then(module => { 
  let jsPDF = module.default
  let pdf = new jsPDF({
    orientation: 'p',
    unit: 'mm',
    format: 'a4',
    putOnlyUsedFonts: true,
    compress: true,
    precision: 4
  })
});

更新:出于某种原因,module.jsPDF 并非在所有环境中都有效。通过使用 module.default 修复(访问默认导出)....