How to include Underscore.js in angular2 project built using angular-cli

raju picture raju · Jun 4, 2016 · Viewed 13k times · Source

I want to include underscore.js inside angular2 project built using angular-cli. Till now I am unable to do so. I tried so far:

1- npm install underscore --save

2- tsd install underscore

3- script src="node_modules/underscore/underscore.js" , reference in index.html

4- inside system-config.js

/** Map relative paths to URLs. */
var map = {
    'underscore': '../node_modules/underscore/underscore.js'
};
/** User packages configuration. */
var packages = {
    'underscore': '../node_modules/underscore/underscore.js'
};

5- import * as _ from 'underscore';

But underscore.js is not getting copied in 'dist' directory during run-time , and browser complain of not finding underscore.js. I think I am missing something at Point#4. Any help is much appreciated as I am beginning learning angular2. Please remember that this project is made by angular-cli, and not by any other seed project. Other than Underscore.js, project is working fine.

[EDIT] package.json has "underscore": "^1.8.3" in dependencies

Answer

Leonya picture Leonya · Mar 17, 2017

Using Angular CLI 1.0.0-rc.1, the recommended solution is described here:

Angular2 2.4 How to load external libraries sush as Underscore into angular2.

npm install underscore --save // save to dependencies: required to run
npm install @types/underscore --save-dev // save to dev dependencies: required in dev mode

Then in your component class:

import * as _ from 'underscore';
...
subtitle = _.head(['xyz'])

Alternatively, there is another way to load "static" scripts in angular-cli as described here https://www.npmjs.com/package/angular-cli#global-library-installation:

In .angular-cli.json, add it to the scripts array:

"scripts": ["../node_modules/underscore/underscore.js"]

This will load underscore.js, but this is not a good way to make it available for use in your typescript classes.