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

折月煮酒 提交于 2019-12-08 10:12:16

问题


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?


回答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);



回答2:


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




回答3:


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' }


来源:https://stackoverflow.com/questions/42194021/angular2-2-4-how-to-load-external-libraries-sush-as-underscore-into-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!