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.
Step 1: Installing the 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:
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.
Step 2: Add TypeScript Definitions for Underscore
Add the Underscore TypeScript definitions by executing the following command:
tsd install underscore
Step 3: Including Script
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:
Step 4: Configuring SystemJS
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.
Step 5: Importing Module
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();