Dreampie Dreampie - 19 days ago 8
Node.js Question

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.

Answer

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