6

I build an Ionic Project using Ionic 2, Angular 2 and TypeScript to test the framework a bit. I need to include an external library (ntc.js) to my project, since I need it to name hex colors.

I know including a Javascript library to TypeScript should work, since whatever works in JS works in 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. I tried to search for ways to do this but found nothing (might be because Angular 2 and Ionic 2 is still fresh).

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.

What is the good way to do this? Where should I place my .js file in my project directory?

2 Answers 2

9

You import it by adding it to your index.html like any other regular javascript file.

Then in your ts file you do:

declare var Tree:any; 

Then in your code, you can use the Tree variable, albeit it exists in the Javascript file. this line of code is basically telling the typescript compiler there is a variable out there Tree which it should ignore.

Sign up to request clarification or add additional context in comments.

5 Comments

Okay, but where do I add the .js file? Also, doesn't index.html get rewritten with every build?
I found it! You have to add it in www/ next to index.html and add include it after the others .js files in index.html like <script src="ntc.js"></script>. Thanks a lot :)
so Tree was declared in ntc.js? In what part of the .ts file we should add declare var Tree:any; ?
It is helpful . i create one function name Tree but it is not showing any alert
Thanks Fabien Roy, i remember it worked for me in an angular 2 project without copying the js file into www folder, i had to to copy it in Ionic 2 project
0

Besides doing a declare var which tells ts that the variable exists you can use typings of typescript. 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.

import {lib} from 'libraryname';

1 Comment

I tried to search ntc.js in typings, but I don't think typings has that library.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.