Using External Libraries with Angular 2

Image for post
Image for post

If you’ve started to play around with Angular 2 you might come to the point where you want to include external JS libraries in your project. As Angular 2 is using the SystemJS (https://github.com/systemjs/systemjs) module loader it’s actually very easy to include additional libraries.

Let’s examine the process by including the famous Underscore (http://underscorejs.org/) library.

In the first step the library has to be downloaded and added to the project. The easiest way to do that is using the Node.js Package Manager (NPM) which is used to set up an Angular 2 project anyway. To install the Underscore library open a terminal switch to the project directory and execute the following command:

$ npm install underscore

Alternatively you can open your package.json file and add the underscore package to the dependencies section, as you can see in the following listing:

 [...]
“dependencies”: {
[...]
“underscore”: “^1.8.3”
},
[...]

Then you can simple type

$ npm install

and all dependencies listed in package.json are installed automatically.

In both cases the target location is the node_modules folder in your project directory. After having installed the underscore NPM package you will find the directory nodes_modules/underscore.

Add the Underscore TypeScript definitions by executing the following command:

tsd install underscore

In the folder nodes_modules/underscore you’ll find the file underscore.js which needs to be included in index.html by using the following <script> element:

<script src=”node_modules/underscore/underscore.js”></script>

Now we need to tell SystemJS where to look for Underscore. Include the paths properties in your System.config call and assign an object with property underscore with a string value containing the path to the library file.

System.config({
[...]
paths: {
underscore: ‘./node_modules/underscore/underscore.js’
}
});

Now we are ready to add an import statement in the component file:

import * as _ from ‘underscore’;

After having imported the module, you can use the underscore library in the component implementation, e.g you can call the uniqueId method to generate a unique identifier:

let myId = _.uniqueId();

Angular 2 — A Practical Introduction To The New Web Development Platform

Written by

Full-stack Web Developer, CodingTheSmartWay.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store