2017-02-12 31 views
0

我用angular-cli創建了一個應用程序,我需要導入外部庫,例如下劃線。我是新的角2.4,並沒有使用SystemJS和Webpack之前。有人可以給我一步一步的指導如何加載下劃線到我的角度2.4項目。Angular2 2.4如何將外部庫sush作爲Underscore加載到angular2中。

帶有下劃線的angular-cli「latest version」創建項目的github鏈接會讓我感到非常高興。讀代碼是好的;)

----下面只是描述是什麼讓我困惑------

從我的研究,我發現2層的替代品來加載模塊。

  1. SystemJS - 大多數記錄在angular.io
  2. 的WebPack - 就是角CLI使用。

哪一個最適合使用?

//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" }

CLI創建的一個參考腳本標籤 「NG服務」。我應該刪除該行並將其替換爲webpack?

......如果是這樣。我是否必須設置角度已完成的所有設置加上我的,還是更簡單的方法,你只需在頂部添加我的設置?

回答

1

使用以下命令:對於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 

在組件:

import * as _ from 'underscore'; 

let rs = _.map([1, 2, 3], function(num){ return num * 3; }); 
console.log(rs); 
+0

謝謝你。 –

1

只要運行npm install --save underscore @types/underscore

+0

當提供一個命令來運行,請務必解釋一下這個命令確實。大多數讀者會理解這些基礎知識(即知道'npm install --save'安裝的東西),但'@ types/underscore'相對較少,因此應該進行解釋。 –

0

要使用下劃線,你需要輸入的類型,所以打字稿編譯器知道它。

npm install --save underscore @types/underscore 

其次,下劃線1.6:

下劃線現在註冊本身AMD(Require.js),鮑爾和 組件,以及作爲一個CommonJS的模塊和常規 (Java )腳本。一個醜陋,但也許是一個必要的。

因此,您需要使用與AMD或CommonJS兼容的模塊加載程序。 SystemJS幾乎可以加載任何格式,因此您可以使用SystemJS並在您的tsconfig文件中定位「commonjs」。

確保您在systemjs.config.js地圖(不包括從index.html中的腳本):

map: { 'underscore': 'npm:underscore/underscore.js' }