Angular 2 AOT报错:无法找到名称,SVGMorpheus全局库引入求助
解决Angular 2/TypeScript项目中SVGMorpheus全局库AOT编译报错问题
我之前也碰到过类似的全局第三方库在Angular AOT编译下的报错情况,针对SVGMorpheus这种没有模块定义和类型声明文件的库,你可以按以下步骤来解决:
确认脚本已正确引入angular-cli.json
先确保你已经把SVGMorpheus的脚本文件添加到了angular-cli.json的scripts数组里,比如如果是通过npm安装的,路径大概是这样:"scripts": [ "../node_modules/svg-morpheus/dist/svg-morpheus.min.js" ]注意路径要和你项目的实际文件位置对应,手动下载的话就填本地文件的相对路径。
添加自定义类型声明文件
因为SVGMorpheus没有官方的.d.ts文件,TypeScript编译器不知道这个全局变量的存在,所以我们要自己声明它:- 在你的项目
src目录下创建一个typings.d.ts文件(如果已经有这个文件就直接用); - 在文件里添加全局变量的基础声明:
// 让TS识别这个全局变量 declare var SVGMorpheus: any;
如果想要更友好的类型提示,还可以根据SVGMorpheus的API补充具体的接口定义:
declare interface SVGMorpheusTransitionOptions { duration?: number; easing?: string; rotation?: string; // 其他你用到的配置项 } declare class SVGMorpheus { constructor(elementSelector: string | Element); to(targetShapeId: string, options?: SVGMorpheusTransitionOptions): void; // 补充库的其他方法 } declare var SVGMorpheus: typeof SVGMorpheus;- 在你的项目
在组件中安全访问全局变量
直接使用全局变量可能在AOT编译时出现识别问题,推荐通过window对象来获取,确保AOT能正确解析:import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html' }) export class YourComponent implements OnInit { private morpher: any; ngOnInit(): void { // 通过window访问全局的SVGMorpheus const svgMorpheus = (window as any).SVGMorpheus; this.morpher = new svgMorpheus('#your-svg-container'); } triggerMorph(): void { this.morpher.to('target-shape-id', { duration: 1000 }); } }重新编译项目
做完以上步骤后,重启ng serve或者执行ng build --aot,应该就不会再出现Cannot find name的报错了。
内容的提问来源于stack exchange,提问作者dudewad
相关产品推荐
相关产品推荐

