Angular在组件使用中包含CDN

Vol*_*iuk 8 typescript angular

我有CDN URL,我想在Component TypeScript文件中使用它。

在Angular 2和更高版本中处理CDN的“正确”方法是什么?

Dav*_*vid 16

如果希望用户从CDN检索js / css文件,则需要将这些文件包括在index.html中。momentjs示例(注意:这只是一个示例,可以通过npm在您的项目中安装momentjs)

index.html

<!-- get script from CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js" />
Run Code Online (Sandbox Code Playgroud)

然后,要在组件中使用脚本,您需要手动声明导出的变量/函数,以避免TS编译错误

component.ts

declare let moment: any; //declare moment

//use moment
moment().format(....);
Run Code Online (Sandbox Code Playgroud)

注意:有些库具有可以代替使用的类型any。您可以从@types存储库获取这些类型