简体   繁体   English

如何在Ionic 2 TypeScript项目中包含外部Javascript库?

[英]How to include external Javascript library in an Ionic 2 TypeScript project?

I build an Ionic Project using Ionic 2, Angular 2 and TypeScript to test the framework a bit. 我使用Ionic 2,Angular 2和TypeScript构建了一个离子项目来测试框架。 I need to include an external library ( ntc.js ) to my project, since I need it to name hex colors. 我需要在我的项目中包含一个外部库( ntc.js ),因为我需要它来命名十六进制颜色。

I know including a Javascript library to TypeScript should work, since whatever works in JS works in TS. 我知道包含一个Javascript库到TypeScript应该工作,因为JS中的任何工作都适用于TS。 I just don't want to include it the wrong way. 我只是不想以错误的方式包含它。

I tried to add the library to www/build/js, but it doesn't seem to work and it doesn't seem like the good way to do this. 我试图将库添加到www / build / js,但它似乎不起作用,它似乎不是这样做的好方法。 I tried to search for ways to do this but found nothing (might be because Angular 2 and Ionic 2 is still fresh). 我试图寻找方法来做到这一点,但没有发现任何东西(可能是因为Angular 2和Ionic 2仍然是新鲜的)。

Things like : 像 :

import * as ntc from '../../js/ntc';

doesn't seem to work as well, even if my library is located at the right place. 即使我的图书馆位于正确的地方,似乎也没有效果。 TypeScript doesn't seem to read my file properly, if it reads it at all. TypeScript似乎没有正确读取我的文件,如果它完全读取它。

What is the good way to do this? 这样做的好方法是什么? Where should I place my .js file in my project directory? 我应该将我的.js文件放在我的项目目录中?

You import it by adding it to your index.html like any other regular javascript file. 您可以通过将其添加到index.html来导入它,就像任何其他常规JavaScript文件一样。

Then in your ts file you do: 然后在你的ts文件中你做:

declare var Tree:any; 

Then in your code, you can use the Tree variable, albeit it exists in the Javascript file. 然后在您的代码中,您可以使用Tree变量,尽管它存在于Javascript文件中。 this line of code is basically telling the typescript compiler there is a variable out there Tree which it should ignore. 这行代码基本上是告诉typescript编译器,那里有一个变量,它应该忽略Tree。

Besides doing a declare var which tells ts that the variable exists you can use typings of typescript. 除了做一个声明var,告诉ts变量存在,你可以使用打字稿的打字。 By writing 通过写作

typings install libraryname

In your console you get a file that already has declare var/class and you can see all of its functions/properties when you import it. 在您的控制台中,您将获得一个已声明var / class的文件,您可以在导入时查看其所有函数/属性。

import {lib} from 'libraryname';

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

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