Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using relative path for templateUrl in Angular2+Webpack

import {Component} from 'angular2/core';

@Component({
  selector: 'app',
  styleUrls: ['./app.component.less'],
  templateUrl: './app.component.html'
})
export class AppComponent {
  name:string = 'Demo'
}

When using the relative path for templateUrl and styleUrls, I get: error 404, file not found:

zone.js: 101 GET http://localhost/app.component.html 404 (Not Found)

code: https://github.com/Dreampie/angular2-demo

I think this is not good design,because under different circumstances may build directory is not the same, can I change it to relative current path?

raw-loader can resolve this,but html-loader,less-loader not work for template,styles,it only work in string,so why not suport them?

import {Component} from 'angular2/core';

@Component({
  selector: 'app',
  styles: [require('./app.component.less')],
  template: require('./app.component.html')
})
export class AppComponent {
  name:string = 'Demo'
}

get other error:

browser_adapter.js:77 EXCEPTION: Error during instantiation of Token Promise<ComponentRef>!.BrowserDomAdapter.logError
browser_adapter.js:77 ORIGINAL EXCEPTION: Expected 'styles' to be an array of strings.
like image 296
Dreampie Avatar asked Apr 23 '16 16:04

Dreampie


2 Answers

Let me add some more information.

Why can't Angular calculate the HTML and CSS URLs from the component file's location?

Unfortunately, that location is not readily known. Angular apps can be loaded in many ways: from individual files, from SystemJS bundles, or from CommonJS bundles, to name a few. With this diversity of load strategies, it's not easy to tell at runtime where these files actually reside.

The only location Angular can be sure of is the URL of the index.html home page. So by default it resolves template and style paths relative to the URL of index.html. That's why we previously wrote our CSS file URLs with an app/ base path prefix.

Official Angular Docu

like image 122
Rose Nettoyeur Avatar answered Nov 07 '22 03:11

Rose Nettoyeur


The ./ (single dot) notation works for ts paths only, it doesn't work with html or css paths.

These paths are relative to index.html, so according to your file structure, this should work

@Component({
  selector: 'app',
  styleUrls: ['app.component.less'],
  templateUrl: 'app.component.html'
})
like image 1
Ankit Singh Avatar answered Nov 07 '22 02:11

Ankit Singh