如何为SystemJS和Webpack的angular 2组件templateUrl编写单个URL?

时间:2016-10-26 08:26:18

标签: angularjs webpack systemjs

我发现SystemJSAngular2 @Component templateUrls字符串中的Webpack项目构建必须不同。

对于SystemJS:

@Component({
    selector: 'home'
    templateUrl: './app/home/home.component.html'
})
export class HomeComponent implements OnInit, OnDestroy {
    ...
}

对于Webpack:

@Component({
    selector: 'home'
    templateUrl: './home.component.html'
})
export class HomeComponent implements OnInit, OnDestroy {
    ...
}

对于SystemJS构建templateUrl字符串必须是root的完整路径。对于Webpack templateUrl,必须是来自root的非完整路径(位于一个位置的组件和组件描述*.ts文件的html模板)。可以为SystemJSWebpack编写单个templateUrl字符串吗?对于mutch quicker switch beetwen SystemJS/Webpack。我尝试使用templateUrl的变量字符串:

import { loginComponentTemplateUrl } from '../shared/url-routing-provider';

@Component({
    templateUrl: loginComponentTemplateUrl 
})

url-routing-provider.ts

export var systemjs: boolean = true;
export var loginComponentTemplateUrl: string = (systemjs) ? './login.component.html' : './app/login/login.component.html';
export default systemjs;

对于SystemJS它适用(对于AMD模式),但Webpack没有。我的帖子与此相关:How declare and import variable into component on angular 2 webpack?

1 个答案:

答案 0 :(得分:0)

要使用systemJs模块加载器的相对路径,您可以set the moduleId。但是,当您切换到使用数字模块标识符的webpack时,此技巧不起作用。

适用于 webpack和system.js的解决方案:

@Component({
   moduleId: typeof module.id == "string" ? module.id : null,
   selector: 'home'
   templateUrl: './home.component.html'
})
export class HomeComponent implements OnInit, OnDestroy {
  ...
}

它有效,但我不能说它很漂亮。