Joseph Genchik
Joseph Genchik

Reputation: 1841

How to use a third party js library in Angular 2 / Typescript application?

I am trying to use a third party .js library in Angular 2 / Typescript application. There are some examples on the web (like using declare var libraryVar: any;) but nothing seems to work. Is there a one correct way to integrate a .js library into a Typescript / Angular2 ?

Upvotes: 3

Views: 4823

Answers (3)

Corey Alix
Corey Alix

Reputation: 2750

The web is full of examples of typescript projects consuming 3rd party libraries.

Here is one of mine which uses arcgis-js-api.

And Here is one that uses openlayers.

In your case you would try this:

bower init
bower install node-uuid --save
tsd install uuid --save

Then setup your tsconfig.json file. I think Angular 2 uses systemjs so you'd want to set module="system" (see system) unless you have a reason not to.

I haven't had much luck with systemjs but you might need to do something like this to get it to load uuid or any other AMD modules:

window.define = System.amdDefine;
window.require = System.amdRequire;

See system-api for an explanation.

Upvotes: 1

basarat
basarat

Reputation: 276171

There are some examples on the web (like using declare var libraryVar: any;) but nothing seems to work. Is there a one correct way to integrate a .js library into a Typescript / Angular2

Perhaps you forgot to put the declare var libraryVar:any; in a vendor.d.ts file that has no root level import/exports.

More : https://basarat.gitbooks.io/typescript/content/docs/types/migrating.html

Upvotes: 3

C B
C B

Reputation: 2000

The best way I have found to use an external library is to create a variable for it at the top of your typescript and import the js. By doing so the variable will offer all the functions the library provides inside your TS without any extra work.

for example if you want to use moment.js to do some time computation. add this to your ts file

var moment = require("./scripts/moment");

after that you can use the functions inside your typescript by directly using the variable

moment.fromNow("SOMEDATE");

I faced the exact problem couple of days ago and I saw this is a good fit, Another neat way is to create a typescript class with all the helpers and reference the typescript to your file and call the helpers within. Still experimenting on a solid pattern, but this would be the start point.

Upvotes: 0

Related Questions