angular 2 – adding 3rd party libs

When including 3rd party libraries, there are two parts… the javascript code you want to execute, and the definition files to give the IDE all it’s strongly-typed goodness.

Obviously, the first must be present if the app is to function. The easiest way to get that is to include the 3rd party library with a <script src="https://stackoverflow.com/questions/35796961/thirdLib.js"> tag in the html page that hosts your Angular 2 app. That will not get you definitions, so you will not have IDE goodness, but the app will function. (to stop the IDE from complaining that it doesn’t know about variable ‘thirdLib’, add declare var thirdLib:any to your ts file. Because it is of type any the IDE will not offer code-completion for thirdLib, but it will also not throw IDE errors.)

To get executing code and definitions, if the lib was written in Typescript, you can add a reference to that ts file from your code with import {thirdLib} from 'thirdLibfolder/thirdLib'. The lib’s ts file by its nature has both the executing code and the typescript definitions.

If the lib is not written in Typescript, but some good soul wrote a thirdLib.d.ts definition file for it, you can reference the d.ts file with /// <reference path="thirdLibfolder/thirdLib.d.ts" /> in your ts file. And then still include the actual executing javascript with the script reference as mentioned above.

The location of these files, and whether you include extensions in the reference, are specific to your project setup and the bundler and build tool you are using. Webpack will search node_modules folder for libraries referenced in the import {... and will accept a reference with .ts extension and without. Meteor will throw an error if you include the .ts extension.

Leave a Comment