I trying to create an application with angular 2,and want use underscore.js library in my .ts files ,for example when i want use this function :
let myId
I have included this library for Angular 4.0.2 using this way:
npm install underscore --save
npm install @types/underscore --save
systemjs.config.js
map: {
// our app is within the app folder
'app': 'app',
.....
// other libraries
'rxjs': 'npm:rxjs',
'underscore': 'npm:/underscore/underscore.js'
}
Finally:
import * as _ from 'underscore';
For a project based on https://cli.angular.io, I needed to do the following:
1) Import libraries
npm install underscore --save
npm install @types/underscore --save
2) in tsconfig.app.json, add underscore to array 'types':
"types": [
"underscore"
]
3) In any component file I need to use underscore, I add this
import * as _ from 'underscore';
4) then I can use:
console.log('now: ', _.now());
and all functions of http://underscorejs.org
For a project based on the angular2-seed, I needed to:
Install underscore package:
npm install underscore --save
Add following to typings.json under globalDependencies:
"underscore": "github:DefinitelyTyped/DefinitelyTyped/underscore",
Add following under project.config.ts:
this.SYSTEM_CONFIG_DEV.paths['underscore'] =
`${this.APP_BASE}node_modules/underscore`;
this.SYSTEM_BUILDER_CONFIG.packages['underscore'] = {
main: 'underscore.js',
defaultExtension: 'js'
};
Import "_" in my ts files:
import * as _ from 'underscore';
You need to install underscore.d.ts typings in your project to use its js library. Check this to know how to include typings
You have to Add TypeScript Definitions for Underscore:
tsd install underscore
Configure SystemJS
System.config({
[...]
paths: {
underscore: './node_modules/underscore/underscore.js'
}
});
Finally import the Module
import * as _ from 'underscore';
Check this repo. It has an example for underscore
https://github.com/angular/angular-cli/wiki/3rd-party-libs#adding-underscore-library-to-your-project
I did this on my imports to make it work
//Place this at the top near your imports
/// <reference path="../../../../typings/globals/underscore/index.d.ts" />
import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import * as _ from 'underscore';
Make sure you have the right reference path to underscore typings.