使用SystemJS在Angular 2中导入应用程序模块

时间:2016-12-19 21:03:40

标签: angular typescript systemjs

我正在使用SystemJS处理带有Typescript项目的Angular 2。现在我经常发现我们经常需要做像../../../'根据我们在给定组件中的嵌套深度,从其他模块加载组件。看起来使用SystemJS的地图设置可以让我在没有那种可怕的相对路径方法的情况下使用应用程序范围的模块进行导入,但我无法确定是否可以这样做。我也愿意采取其他方式来解决这个问题。

基本上我想做的就是这样:

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

我知道可能有其他方法可以做到这一点,但又无法找到任何确定的内容,这是我真正想要解决的问题。再次感谢!

1 个答案:

答案 0 :(得分:0)

您可以设置typescript编译器以使用基本URL并从那里导入。在tsconfig.json添加:

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

然后你可以使用app root作为绝对路径。像

这样的东西
import {SecureHttpClient} from 'app/mySecurityModule';

而不是:

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

实际路径可能与您有所不同。

但是,我建议为编辑器使用某种Import扩展(例如,AutoImport用于VSCode),因为某些工具(AoT,CLI)可能存在此问题。希望随着工具变得更加成熟,事情会有所改善(;

相关问题