Using require to set templateUrl in Angular 2 whil

2020-05-09 03:59发布

问题:

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 Error: TypeError: require is not a function at eval (http://localhost:3000/app/header/header.js:29:35) at execute (http://localhost:3000/app/header/header.js:34:14) Error loading 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')

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"
  ]
}

回答1:

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

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

Example:

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

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

Example:

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

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



回答2:

Instead of require just use a relative path from the root of your document.

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