Typescript+Stenciljs项目集成pdfmake初始化失败如何解决?
问题原因
- 导出结构不匹配:你当前使用的pdfmake版本中,
vfs_fonts模块的导出结构和旧版本不同,不需要通过pdfFonts.pdfMake.vfs的路径访问vfs对象,尝试读取不存在的pdfMake属性就会触发第一个报错。 - 顶层代码执行异常阻断组件注册:你将vfs赋值的操作写在组件顶层,代码抛出异常后会阻断后续组件类的注册逻辑,所以Stencil加载组件时会提示找不到构造函数。
解决方案
方案1:适配导入结构(适合大多数情况)
直接修改vfs赋值逻辑,兼容不同版本的导出结构即可:
import * as pdfMake from "pdfmake/build/pdfmake"; import * as pdfFonts from 'pdfmake/build/vfs_fonts'; (pdfMake as any).vfs = pdfFonts.default?.pdfMake?.vfs ?? pdfFonts.pdfMake?.vfs ?? pdfFonts.default ?? pdfFonts;
如果不需要兼容旧版本,直接用(pdfMake as any).vfs = pdfFonts.default ?? pdfFonts即可。
方案2:动态导入避免顶层报错
如果调整导入结构后还是有问题,可以将pdfmake的初始化逻辑放到组件生命周期中执行,避免顶层代码异常影响组件注册:
import { Component, h, ComponentWillLoad } from '@stencil/core'; @Component({ tag: 'my-messages', styleUrl: 'my-messages.css', shadow: true, }) export class MyMessages implements ComponentWillLoad { private pdfMakeInstance: any; async componentWillLoad() { const pdfMakeModule = await import('pdfmake/build/pdfmake'); const pdfFontsModule = await import('pdfmake/build/vfs_fonts'); this.pdfMakeInstance = pdfMakeModule.default ?? pdfMakeModule; this.pdfMakeInstance.vfs = pdfFontsModule.default?.pdfMake?.vfs ?? pdfFontsModule.vfs ?? pdfFontsModule; } // 生成PDF的调用示例 handleExportPdf() { const docConfig = { content: 'PDF测试内容' }; this.pdfMakeInstance.createPdf(docConfig).download('export.pdf'); } render() { return <button onClick={() => this.handleExportPdf()}>导出PDF</button>; } }
补充注意事项
- 若出现vfs只读的TS报错,可以在
tsconfig.json的compilerOptions中添加"allowSyntheticDefaultImports": true配置,优化CommonJS模块的导入适配。 - 如果你使用的是pdfmake 0.2.x以上版本,内置了TS类型定义,不需要额外安装
@types/pdfmake依赖。
内容的提问来源于stack exchange,提问作者user1107888
相关产品推荐
相关产品推荐

