在 Angular 2 中使用 require 设置 templateUrl 时出现错误

2024-04-11

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

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 () {

  }

}

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

angular2-polyfills.js:332 错误: TypeError: require 不是函数 在评估时(http://localhost:3000/app/header/header.js:29:35 http://localhost:3000/app/header/header.js:29:35) 在执行时(http://localhost:3000/app/header/header.js:34:14 http://localhost:3000/app/header/header.js:34:14) 错误加载http://localhost:3000/app/main.js http://localhost:3000/app/main.js

我希望能够做这样的事情:(我确实知道解决方法,但我只是想了解更多,如何以其他方式使其工作)

// 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

{
  "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('./hahaha.html')将是模板字符串,但是templateUrl场预计PATH到 .html 模板。

解决方案1: use template如果您想继续,请输入字段require功能

Example:

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

解决方案2: use templateUrl但在这种情况下,您必须指向 .html 模板的路径

Example:

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

Update:如果有templateUrl- 模板加载应该是异步的(AMD),但是template- 模板将内联到 JavaScript 中

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Angular 2 中使用 require 设置 templateUrl 时出现错误 的相关文章

随机推荐