0

I created an app with angular-cli and I need to import external libraries such as underscore. I'm new to angular 2.4 and haven't used SystemJS nor Webpack before. Can someone give me a step by step guid of how to load underscore into my angular 2.4 project.

A link to github with a project created with angular-cli "latest version" with underscore would make me super happy. Reading code is nice ;)

---- Following is just to describe what makes me confused ------

From my research I found 2 alternatives to load modules.

  1. SystemJS - Most documented in angular.io
  2. Webpack - Is what angular-cli is using.

Which one is best to use?

//package.json "name": "angular", "version": "0.0.0", "license": "MIT", "angular-cli": {}, "scripts": { "ng": "ng", "start": "ng serve", "test": "ng test", "pree2e": "webdriver-manager update --standalone false --gecko false", "e2e": "protractor" }

The cli creates a reference to "ng serve" in the script tag. Should I remove that line and replace it with webpack?

... If so. Do I have to set up all the settings angular already done plus mine or is it an easier way you just add my settings on top?

3 Answers3

1

Just run npm install --save underscore @types/underscore

Tuong Le
  • 18,533
  • 11
  • 50
  • 44
  • When providing a command to run, please make sure to explain what that command does. Most people reading this will understand the basics (i.e. know `npm install --save` installs things) but the `@types/underscore` is relatively rare, and as such should be explained. – Nic Feb 12 '17 at 23:22
1

using following commands: For Angular CLI

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

in Component:

import * as _ from 'underscore';

let rs = _.map([1, 2, 3], function(num){ return num * 3; });
console.log(rs);
Tiep Phan
  • 12,386
  • 3
  • 38
  • 41
0

To use underscore, you need to import types, so the typescript compiler knows about it.

npm install --save underscore @types/underscore 

Second, as of underscore 1.6:

Underscore now registers itself for AMD (Require.js), Bower and Component, as well as being a CommonJS module and a regular (Java)Script. An ugliness, but perhaps a necessary one.

So you need to use a module loader that is compatible with AMD or CommonJS. SystemJS can load virtually any format, so you could use SystemJS and target "commonjs" in your tsconfig file.

Make sure you include the map in systemjs.config.js (don't include the script from index.html):

map: {  'underscore': 'npm:underscore/underscore.js' }
Michael Kang
  • 52,003
  • 16
  • 103
  • 135