(2017-03-13)更新:
删除了所有提到的 moduleId。 “组件相对路径”说明书已删除
我们在推荐的 SystemJS 配置中添加了一个新的 SystemJS 插件 (systemjs-angular-loader.js)。该插件会为您动态地将 templateUrl 和 styleUrls 中的“组件相对”路径转换为“绝对路径”。
我们强烈建议您只编写相对于组件的路径。这是这些文档中讨论的唯一形式的 URL。你不再需要写@Component({ moduleId: module.id }),也不应该。
来源:https://angular.io/docs/ts/latest/guide/change-log.html
定义:
moduleId?: string
@Component 注释内的moduleId 参数采用string 值,即;
"包含该组件的模块的模块ID。"
CommonJS 用法:module.id,
SystemJS 用法:__moduleName
使用moduleId的原因:
moduleId 用于解析样式表和模板的相对路径,如文档中所述。
包含该组件的模块的模块 ID。需要能够解析模板和样式的相对 URL。在 Dart 中,这可以自动确定,不需要设置。在 CommonJS 中,这总是可以设置为 module.id。
参考(旧):https://angular.io/docs/js/latest/api/core/index/ComponentMetadata-class.html
我们可以通过设置@Component元数据的moduleId属性来指定模板和样式文件相对于组件类文件的位置
参考:https://angular.io/docs/ts/latest/cookbook/component-relative-paths.html
使用示例:
文件夹结构:
RootFolder
├── index.html
├── config.js
├── app
│ ├── components
│ │ ├── my.component.ts
│ │ ├── my.component.css
│ │ ├── my.component.html
没有 module.id:
@Component({
selector: 'my-component',
templateUrl: 'app/components/my.component.html', <- Starts from base path
styleUrls: ['app/components/my.component.css'] <- Starts from base path
})
带有module.id:
tsconfig.json:
{
"compilerOptions": {
"module": "commonjs", <- need to change this if you want to use module.id property
...
@Component({
moduleId: module.id,
selector: 'my-component',
templateUrl: 'my.component.html', <- relative to the components current path
styleUrls: ['my.component.css'] <- relative to the components current path
})