简体   繁体   English

如何在angular5项目中导入外部js文件?

[英]How to import external js file in angular5 project?

I've just joined an angular 5 project (new to the tech). 我刚刚加入了angular 5项目(对技术而言是新的)。 I need to use functions from an external javascript file. 我需要使用外部javascript文件中的函数。

I found some information here : How to include external js file in Angular 4 and call function from angular to js 我在这里找到了一些信息: 如何在Angular 4中包含外部js文件以及如何将函数从angular调用到js

But it doesn't work. 但这是行不通的。 What am I doing wrong ? 我究竟做错了什么 ?

  1. I added my js file in the project and declared it in the .angular-cli.json : "scripts": [ "./assets/js/kia.js" ], 我在项目中添加了我的js文件,并在.angular-cli.json中声明了它: "scripts": [ "./assets/js/kia.js" ],

  2. Then I declared it in the typings.d.ts : declare var kia: any; 然后我在types.d.ts中声明了它: declare var kia: any;

  3. And finally I tryed to import it in the file I use detail.component.ts : import * as variable from 'kia'; 最后,我尝试将其导入我使用detail.component.ts的文件中: import * as variable from 'kia';

I've the error : error TS2307: Cannot find module 'kia'. 我有错误: 错误TS2307:找不到模块'kia'。

Anyone knows how to fix this ? 有人知道如何解决这个问题吗?

You can include it in your index.html as you would normally (inside a script tag) and if necessary add the type definitions in your typings.d.ts or preferably, find a @types package for it. 您可以像平常一样(在脚本标记中)将其包含在index.html中,如有必要,可以在types.d.ts中添加类型定义,或者最好为它找到@types包。

Otherwise you can do what you are doing. 否则,您可以做您正在做的事情。 Just ensure you path is correct and then since you've added it to your typings file you do not need to import it at the top of your ts file, you can just reference it like. 只要确保您的路径正确无误,然后由于您已将其添加到类型文件中,则无需将其导入ts文件的顶部,就可以像这样引用它。

const a = kia. ...

If you've installed it using an npm package then you should rather import it, as you are doing 如果您使用npm软件包安装了它,那么您应该像导入时那样导入它

I solved this probleme by removing the import in the component.ts, then add a link method(); 我通过删除component.ts中的导入解决了这个问题,然后添加了link method();。 in the component.html, and declaring method() { kia.test();} in the componant.ts. 在component.html中,并在componant.ts中声明method(){kia.test();}。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM