StencilJS+Typescript项目集成pdfmake触发属性读取报错如何解决
StencilJS集成pdfmake报错修复方案
报错1:TypeError: Cannot read properties of undefined (reading 'pdfMake')修复
- 该报错是因为ES模块导入规则下,
vfs_fonts的导出结构与你引用的格式不匹配,将vfs赋值代码替换为兼容写法即可:
// 替换原来的 (<any>pdfMake).vfs = pdfFonts.pdfMake.vfs; (<any>pdfMake).vfs = (pdfFonts.pdfMake ?? pdfFonts).vfs;
- 检查
moment依赖是否完整:你的代码中使用了moment处理日期,缺失该依赖会导致类初始化失败,先执行安装命令npm install moment,再在服务代码头部补充导入:
import moment from 'moment';
报错2:Uncaught (in promise) Error: Constructor for "my-messages#undefined" was not found修复
该报错是因为pdfmake是纯客户端运行的库,不能在Stencil的预渲染/服务端渲染阶段初始化,调整服务实例化时机即可:
- 不要在
my-messages组件的构造函数、componentWillLoad生命周期中实例化PDFCreateService - 改为在客户端专属的
componentDidLoad生命周期中实例化服务,或者在用户触发的事件(比如按钮点击)中按需实例化
完整修正代码示例
修正后的PDFCreateService代码
import * as pdfMake from 'pdfmake/build/pdfmake'; import * as pdfFonts from 'pdfmake/build/vfs_fonts'; import moment from 'moment'; (<any>pdfMake).vfs = (pdfFonts.pdfMake ?? pdfFonts).vfs; export class PDFCreateService { constructor() {} public createNachrichtPDF(message: string): any { const fileName: string = 'ba-postfach-' + moment(new Date()).format('DD-MM-YYYY'); const docDefinition = { content: [message] }; return pdfMake.createPdf(docDefinition); } }
修正后的my-messages组件调用示例
import { Component, h } from '@stencil/core'; import { PDFCreateService } from './pdf-create.service'; // 替换为你的服务实际路径 @Component({ tag: 'my-messages', styleUrl: 'my-messages.css', shadow: true }) export class MyMessages { private pdfService: PDFCreateService; componentDidLoad() { // 客户端挂载完成后再实例化服务 this.pdfService = new PDFCreateService(); } private exportPDF() { const pdfInstance = this.pdfService.createNachrichtPDF('测试导出内容'); pdfInstance.download(); } render() { return ( <div> <button onClick={() => this.exportPDF()}>导出消息PDF</button> </div> ) } }
可选兼容配置
如果仍有模块加载异常,可以在stencil.config.ts中将pdfmake标记为外部依赖,避免rollup打包时出现兼容问题:
import { Config } from '@stencil/core'; export const config: Config = { // 其余原有配置保留 externals: ['pdfmake'] };
内容的提问来源于stack exchange,提问作者user1107888
相关产品推荐
相关产品推荐

