10

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

7 Answers 7

8

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.

Sign up to request clarification or add additional context in comments.

Comments

4

install underscore using npm Go to yourappname/src/typings.d.ts and add this line declare module 'underscore'; then run ng build

Comments

2

Angular 2 full 3 file snippets

package.json

    {
  "name": "angular2-quickstart",
  "version": "1.0.0",
  "scripts": {
    "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ",
    "lite": "lite-server",
    "postinstall": "typings install",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "typings": "typings"
  },
  "license": "ISC",
  "dependencies": {
    "@angular/common": "2.0.0",
    "@angular/compiler": "2.0.0",
    "@angular/core": "2.0.0",
    "@angular/forms": "2.0.0",
    "@angular/http": "2.0.0",
    "@angular/platform-browser": "2.0.0",
    "@angular/platform-browser-dynamic": "2.0.0",
    "@angular/router": "3.0.0",
    "@angular/upgrade": "2.0.0",
    "angular2-in-memory-web-api": "0.0.20",
    "bootstrap": "^3.3.6",
    "core-js": "^2.4.1",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.12",
    "systemjs": "0.19.27",
    "tsd": "^0.6.5",
    "underscore": "^1.8.3",
    "zone.js": "^0.6.23"
  },
  "devDependencies": {
    "concurrently": "^2.2.0",
    "lite-server": "^2.2.2",
    "typescript": "^2.0.2",
    "typings": "^1.3.2"
  }
}

systemjs.config.js

/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',
      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
      // other libraries
      'rxjs':                       'npm:rxjs',
      'underscore':                 'npm:underscore',

      'angular2-in-memory-web-api': 'npm:angular2-in-memory-web-api',
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './main.js',
        defaultExtension: 'js'
      },


      rxjs: {
        defaultExtension: 'js'
      },
      'underscore':{
       main: './underscore.js', 
       defaultExtension: 'js'
       },
      'angular2-in-memory-web-api': {
        main: './index.js',
        defaultExtension: 'js'
      }
    }
  });
})(this);

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  }
}

typings.json

{
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160725163759",
    "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
    "node": "registry:dt/node#6.0.0+20160909174046"
  },
  "ambientDependencies": {
    "underscore": "github:DefinitelyTyped/DefinitelyTyped/underscore/underscore.d.ts#f0990e288ac73d593e982995947567aa2643b828"
  }
}

1- npm install underscore --save 2- tsd install underscore (if tsd not install first install that) 3) now do npm install 4) then npm start

Comments

1

install underscore:

npm i underscore --save

in angular-cli.json:

"scripts": [
        "../node_modules/underscore/underscore-min.js",
         ...
      ],

after run command:

ng build

in component:

declare var _: any;
@Component({...})

Comments

0

Do you have in your project a file called Package.json? If Yes, you can try to add this line

"underscore": "^1.8.3",

in the dependencies of this file.

Modifications in system-config.ts

var map = {

    "underscore": "node_modules/underscore",

  };

var packages = {
    'underscore':            { main: 'index.js', defaultExtension: 'js' }
  };

  var packageNames = [
    '@angular/common',
    '@angular/compiler',
    '@angular/core',
    '@angular/http',
    '@angular/platform-browser',
    '@angular/platform-browser-dynamic',
    '@angular/router-deprecated',
    '@angular/testing',
    '@angular/upgrade',
  ];

packageNames.forEach(function(pkgName) {
    packages[pkgName] = { main: 'index.js', defaultExtension: 'js' };
  });

var config = {
    map: map,
    packages: packages,
    paths: {
      "underscore": "/node_modules/underscore.js"
    }
  };

And to do a npm install after that.

3 Comments

Yes, package.json has this, but it is not updating system-config.ts
If you need to update system-config.ts, you must do it manually, as you did with package.json. And npm install, after all this modifications.
I tried your steps, but when running ng serve, it give error ' Cannot find module Underscore'. Can you please provide a working plnkr for this. Thanks in advance
0

I think you might have missed a step? Did you remember to setup underscore in the "angular-cli-build.js" file? This step tells clingon to put underscore in the vendor folder (/dist/vendor).

Here's how I got underscore working.

  1. Install underscore and typings:

    npm install underscore --save
    typings install underscore --save --ambient
    
  2. Setting up underscore in "angular-cli-build.js":

    module.exports = function(defaults) {
      return new Angular2App(defaults, {
        vendorNpmFiles: [
          'systemjs/dist/system-polyfills.js',
          'systemjs/dist/system.src.js',
          'zone.js/dist/**/*.+(js|js.map)',
          'es6-shim/es6-shim.js',
          'reflect-metadata/**/*.+(js|js.map)',
          'rxjs/**/*.+(js|js.map)',
          '@angular/**/*.+(js|js.map)',
          'moment/moment.js',
          'underscore/underscore.js'
        ]
      });
    };
    
  3. Then underscore get compiled to the vendor folder (/dist/vendor), and now it's possible to point to this location from the system.config.ts file:

    const map: any = {
      "underscore": "vendor/underscore/underscore.js",
      "moment": "vendor/moment/moments.js"
    };
    
    /** User packages configuration. */
    const packages: any = {
      'underscore': {
        format: 'cjs'
      },
      'moment': {
        format: 'cjs'
      }
    };
    

Remember to use the hole path including the .js hope this helps :)

I did the same as with moment, from the docs: https://github.com/angular/angular-cli/wiki/3rd-party-libs

6 Comments

I will definitely try this today.
Please let me know if there's anything I need to elaborate.
typings install underscore --save --global give me this error "typings ERR! message Unable to find "underscore" ("npm") in the registry."
You shouldn't install underscore global. just: npm install underscore --save
Again this error :: typings install underscore --save --global
|
0

I am using Angular-cli, all I did was to add this line in package.json

"underscore": "^1.8.3",

and then I Run:
1. npm install underscore --save
2. npm install

and it worked...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.