2016-12-19 72 views
0

我正在使用SystemJS處理帶有Typescript項目的Angular 2。現在我經常發現我們不得不按照'../../../'這樣的方式從其他模塊加載組件,這取決於我們在給定組件中的嵌套深度。看起來使用SystemJS的映射設置可以讓我在沒有可怕的相對路徑方法的情況下使用應用程序範圍的模塊進行導入,但是我無法確定是否可以這樣做。我也開放其他方式來解決這個問題。使用SystemJS在Angular 2中導入應用程序模塊

基本上我想要做的是這樣的:

import {Component} from '@angular/core'; 
import {SecureHttpClient} from 'mySecurityModule'; //No ../../../ 

@Component({ 
    moduleId: module.id, 
    selector: 'my-selector', 
    templateUrl: 'my.component.html' 
}) 
export class MyComponent { 

    constructor(private client: SecureHttpClient) { 

    } 
} 

我試過配置下,但它不工作(TS編譯失敗)。

(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', 
     '@angular/upgrade': 'npm:@angular/upgrade/bundles/upgrade.umd.js', 


     // other libraries 
     'rxjs':      'npm:rxjs', 
     'angular-in-memory-web-api': 'npm:angular-in-memory-web-api', 
     '@ng-bootstrap/ng-bootstrap': 'npm:@ng-bootstrap/ng-bootstrap/bundles/ng-bootstrap.js', 

     // Internal Modules 
     'mySecurityModule': 'app/secure/secure.module' 

    }, 
    // 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' 
     }, 
     'angular-in-memory-web-api': { 
     main: './index.js', 
     defaultExtension: 'js' 
     } 
    } 
    }); 
})(this); 

我知道有可能其他方法可以做到這一點,但同樣找不到任何明確的,它是我真的想解決的一個問題。再次感謝!

+0

關閉主題的分類,但是會推薦使用jspm來管理外部庫的systemjs配置 – cYrixmorten

回答

0

您可以設置打字稿編譯器使用基本URL並從那裏導入。在tsconfig.json中加入:

"compilerOptions": { 
    "baseUrl": "./", 
    ... 
    } 

然後你可以使用app root作爲絕對路徑。喜歡的東西

import {SecureHttpClient} from 'app/mySecurityModule'; 

代替:

import {SecureHttpClient} from '../../../mySecurityModule'; 

實際的路徑可能是你不同的。但是,我建議在你的編輯器中使用某種導入擴展(例如,VSCode的AutoImport),因爲某些工具(AoT,CLI)可能會遇到問題。希望事情會隨着工具變得更加成熟而改進(

+0

感謝您的迴應我嘗試使用baseUrl並且它適用於tsc編譯(transpilation)在瀏覽器中加載404錯誤時失敗,只有當我執行'../../../'時纔會在瀏覽器中正確加載導入的組件,我正在使用'tsc -w'和'lite-server'(一個John Papa瀏覽器同步擴展)來託管應用程序。 –

相關問題