使用require在角色2中设置templateUrl,同时得到错误 [英] Using require to set templateUrl in Angular 2 while getting error

查看:74
本文介绍了使用require在角色2中设置templateUrl,同时得到错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的组件中,我想使用require设置templateUrl,如下所示:

in my component, I want to set templateUrl using require, like this:

import {Component} from 'angular2/core';


@Component({
    selector: 'header',
    styleUrls: ['app/header/header.css'],
    templateUrl: require('./hahaha.html')
})
export class HeaderComponent {

  logoUrl: string = '/resources/img/branding.png';


  constructor () {

  }

}

在我的控制台中,我收到错误

In my console, I got an error


angular2-polyfills.js:332错误:TypeError:require不是一个函数
在eval( http:/ / localhost:3000 / app / header / header.js:34 :14rel =nofollow> http:// localhost:3000 / app / header / header.js:34:14 )加载 http:// localhost:3000 / app / main.js

我想要这样做:(我知道一个工作,但我只想知道更多,如何使其他方式)

I want to be able to do something like this: (I do know a work around, but I just want to know more, how to make this works in other way)

// Note that this is a relative path, which I will get error for now, I have to write from root path, don't like it.
styleUrls: ['./header.css']  
templateUrl: require('./hahaha.html')

这是我的tsconfig.json

This is my tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "exclude": [
    "node_modules",
    "typings/main",
    "typings/main.d.ts"
  ]
}


推荐答案

require('./ haha​​ha.html')将是模板字符串,但 templateUrl 字段希望<。> PATH 到.html模板。

The result of require('./hahaha.html') will be the template string, but templateUrl field expects the PATH to the .html template.

解决方案1 ​​:使用模板字段如果要继续 require function

Solution 1: use template field if you want to proceed with require function

示例e:

@Component({
  selector: 'header',
  styleUrls: ['app/header/header.css'],
  template: require('./hahaha.html')
})

解决方案2 :使用 templateUrl 但在这种情况下,您必须通过路径。 html模板

Solution 2: use templateUrl but in this case, you have to path to the .html template

示例:

@Component({
  selector: 'header',
  styleUrls: ['app/header/header.css'],
  templateUrl: './hahaha.html'
})

更新:如果 templateUrl - 模板加载应该是异步的(AMD),但是使用模板 - 模板将内联到javascript

Update: in case with templateUrl - template load should be asynchronous(AMD), but with template - template will be inlined into javascript

这篇关于使用require在角色2中设置templateUrl,同时得到错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆