Adding Underscore to a Node. Once added, underscore can be referred in any of the Node. js modules using the CommonJS syntax: var _ = require('underscore'); Now we can use the object underscore (_) to operate on objects, arrays and functions.
UnderscoreJs is a JavaScript Libraries which have several functions which extend functionality without extending any built-in objects. It is comparable to features provided by Prototype.
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
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.
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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With