首页 文章

使用Angular2组件中的templateUrl与SystemJS的相对路径

提问于
浏览
22

我在angular2组件中定义templateUrl时尝试使用相对路径,如下所述:http://schwarty.com/2015/12/22/angular2-relative-paths-for-templateurl-and-styleurls/

@Component({
    selector: 'login-app',
    moduleId: module.id,
    templateUrl: './app.html'
})

虽然我一直在:

错误:未定义模块

我在ts编译设置上使用-m commonjs .

如何使它工作?

9 回答

  • 12

    这根本不适合我 . I can see in the Github repo对于Angular 2来说,该功能据说是在12月初添加的,但它根本无法正常运行 .

    文档尚未更新以反映它,并且它仍然缺少我能说的正确测试 .

    Update:

    这里's part of what'继续 . This requires a CommonJS specific feature工作,所以你必须在tsconfig.json文件中使用该模块系统 .

    最重要的是,there's an issue when using SystemJS因为它将所有内容捆绑到根目录中 .

    基本上,能够使用这个新功能似乎有很多限制 .

  • 1

    您可以尝试以下步骤:

    步骤1.声明'commonjs'格式模块对象,该对象标识当前模块的“模块ID” .

    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        ...
    }
    

    第2步:将typings.d.ts添加到wwwroot文件夹中以标识“模块ID” .

    /// <reference path="../typings/globals/core-js/index.d.ts" />
     declare var module: { id: string };
    

    步骤3:将组件的 moduleId 元数据属性设置为 module.id ,以获取模块相对URL(请注意约定) .

    @Component({
        selector: 'login-app',
        moduleId: module.id,
        templateUrl: 'app.component.html'
    })
    

    希望这有帮助 .

  • 3

    解决方法:使用require with template而不是templateUrl

    @Component({
        selector: 'login-app',
        template: require('./app.html')
    })
    
  • -1

    我有同样的问题:

    错误TS2304:找不到名称'module' .

    由于某些原因,即使在 tsconfig.json 文件中的compilerOptions中使用 "module": "commonjs" ,TypeScript也会出现此错误 . 所以我通过添加声明解决了这个问题:

    declare var module: {
        id: string;
    };
    
  • 4

    只需使用module.id值设置Component的"moduleId"属性即可 . 请参考此处的示例:https://angular.io/docs/ts/latest/cookbook/component-relative-paths.html#!#set-the-moduleid-

    示例代码:@Component({moduleId:module.id,selector:'login',templateUrl:“login.component.html”})

    为我工作 .

  • -1

    使用systemjs,首先声明字符串__moduleName(两个下划线),然后使用它而不是module.id,如下所示:

    declare var __moduleName: string;
    
    @Component({
        selector: 'login-app',
        moduleId: __moduleName,
        templateUrl: './app.html'
    })
    
  • 5

    由于这个问题引起了很多关注 - 我将在 OFFICIAL ANGULAR COOKBOOK 发表一篇好文章的链接:Component-relative Paths

    它解释了 why absolute paths are used by defaulthow to use the relative paths ,具体取决于包装和模块加载策略 .

  • 0

    模块实际上是在节点类型的index.d.ts中定义的 .

    在你的typings.json中添加节点,如下所示,并运行'npm run typings install' .

    {
      "globalDependencies": {
        "core-js": "registry:dt/core-js#0.0.0+20160602141332",
        "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
        "node": "registry:dt/node#6.0.0+20160621231320"
      }
    }
    

    这应该可以解决您的问题 .

  • -2

    使用temlplateUrl时,请使用html文件的绝对路径 . 例如:如果您的应用程序层次结构是MyApp-> app-> yourComponent.ts,那么app.html就在那里,然后按照以下方式解决yourComponent.ts的Component装饰器,它应该可以工作 .

    @Component({selector:'login-app',templateUrl:'app / app.html'})

    即使在将moduleID设置为module.id或任何其他工作之后,相对路径也从未对我有用 . 如果它适用于任何人,请分享 .

相关问题