How write single url for angular 2 component templateUrl for SystemJS and Webpack?

偶尔善良 提交于 2020-01-04 11:01:27

问题


I find out that for SystemJS and Webpack project builds in Angular2 @Component templateUrls string must be different.

For SystemJS:

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

For Webpack:

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

For SystemJS build templateUrl string must be full path from root. For Webpack templateUrl must be non full path from root (html template for component and component description *.ts file located in one location). It is possible to write single templateUrl string for SystemJS and Webpack? For mutch quicker switch beetwen SystemJS/Webpack. I try to use variable string for 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;

For SystemJS it works (for AMD pattern), but for Webpack not. My previos post related for this: How declare and import variable into component on angular 2 webpack?


回答1:


To use relative paths with systemJs module loader you can set the moduleId. This trick, however, does not work when you switch to webpack, which uses numeric module identifier.

A solution that works for both webpack and system.js:

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

It works, but I cannot tell it is pretty.



来源:https://stackoverflow.com/questions/40257238/how-write-single-url-for-angular-2-component-templateurl-for-systemjs-and-webpac

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