Angular集成Vexflow时提示Cannot find name 'FontFace'错误
Angular 12集成VexFlow报FontFace类型不存在编译错误
问题场景
- 执行依赖安装命令:
npm install vexflow - 参照官方示例编写五线谱渲染组件后,启动Angular开发服务抛出编译错误
- 具体报错信息:
Error: node_modules/vexflow/build/types/src/font.d.ts:132:92 - error TS2304: Cannot find name 'FontFace'. 132 static loadWebFont(fontName: string, woffURL: string, includeWoff2?: boolean): Promise<FontFace>;
- 尝试常规类型修复方案后问题未解决。
- 测试组件完整代码:
import {AfterViewInit, Component, ElementRef, OnInit} from '@angular/core'; import {Renderer, Stave} from "vexflow"; @Component({ selector: 'app-note-display', templateUrl: './note-display.component.html', styleUrls: ['./note-display.component.scss'] }) export class NoteDisplayComponent implements OnInit, AfterViewInit { constructor(private elRef: ElementRef) { } ngOnInit(): void { } ngAfterViewInit() { const renderer = new Renderer(this.elRef.nativeElement.querySelector('#note-display'), Renderer.Backends.SVG); renderer.resize(500, 500); const context = renderer.getContext(); const stave = new Stave(10, 40, 400); stave.addClef('treble').addTimeSignature('4/4'); stave.setContext(context).draw(); } }
修复方法
报错根源是TypeScript无法识别浏览器原生FontFace API的类型定义,按以下优先级操作即可解决:
- 打开项目根目录
tsconfig.json,找到compilerOptions.lib配置数组,确保添加"dom"项,引入浏览器DOM相关类型声明:
{ "compilerOptions": { // 保留原有其他配置 "lib": [ "es2018", "dom", "esnext.asynciterable" ] } }
- 若上述操作后仍报错,在
compilerOptions中添加"skipLibCheck": true配置,跳过第三方依赖包的类型校验,规避依赖类型定义和当前项目TypeScript版本不兼容的问题:
{ "compilerOptions": { // 保留原有其他配置 "skipLibCheck": true } }
- Angular 12默认搭配TypeScript 4.2/4.3版本,低于4.4版本的TS内置DOM类型未收录
FontFace声明,可以直接安装兼容低版本TS的VexFlow稳定版:
npm install vexflow@4.0.3
- 所有修改完成后,停止当前开发服务,执行
ng serve重启即可正常编译运行。
内容的提问来源于stack exchange,提问作者ebarooni
相关产品推荐
相关产品推荐

