在Angular2 + Webpack中使用templateUrl的相对path

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

当使用templateUrl和styleUrls的相对path时,我得到:错误404,找不到文件:

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

代码: https : //github.com/Dreampie/angular2-demo

我觉得这是不好的devise,因为在不同的情况下可能会build立目录不一样,我可以把它改成相对的当前path吗?

raw-loader可以解决这个问题,但是html-loaderless-loader不能用于templatestyles ,它只能在string工作,所以为什么不把它们支撑起来呢?

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

得到其他错误:

 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. 

让我再添加一些信息。

为什么Angular不能从组件文件的位置计算HTML和CSS URL?

不幸的是,那个位置不是很容易知道的。 Angular应用程序可以以多种方式加载:从单个文件,从SystemJS软件包或从CommonJS软件包中加载。 有了这种加载策略的多样性,在运行时不易告诉这些文件实际存在的位置。

Angular可以确定的唯一位置就是index.html主页的URL。 因此,默认情况下,它将parsing相对于index.html的URL的模板和样式path。 这就是为什么我们以前使用app / basepath前缀编写我们的CSS文件的URL。

官方的文件

./ (单点)符号仅适用于tspath,它不适用于html或csspath。

这些path是相对于index.html,所以根据你的文件结构,这应该工作

 @Component({ selector: 'app', styleUrls: ['app.component.less'], templateUrl: 'app.component.html' }) 

你需要尝试

 @Component({ selector: 'app', template: require('./app.component.html'), styles: [ require('./app.component.less').toString() or String(require('./app.component.less')) or add css-to-string in your webpack conf ({test: /\.css$/, loaders: ['css-to-string', 'style', 'css']}) }) 

将moduleId属性设置为module.id以进行模块相对加载,以便url相对于组件。

 @Component({ moduleId: module.id, selector: 'app', styleUrls: ['app.component.less'], templateUrl: 'app.component.html' }) 

如果您使用的是SystemJS,请参阅我的答案: https ://stackoverflow.com/a/40694657/986160

您可以使用model.id并将其从您的构buildpath(使用js)转换为使用ts,css和html的构buildpath。 这样,您可以在Angular 2中使用相对path来创build模板和样式

 @Component({ moduleId: module.id.replace("/dist/", "/"), ... }); 

我注意到在我的情况下同样的错误。 的原因

预期的“风格”是一个string数组

在我的情况是用于加载CSS文件和pipe道到angular2-template-loader

我从debugging中了解到, css-loader对CSS文件中的变化有一些“智能”检测,如果没有任何变化,CSS文件就不会被webpack模块导出为string。

因为这只是你好词的应用程序我的解决scheme非常简单:用raw-loaderreplacecss-loader raw-loader 。 这是我的装载机版本:

 loaders: [ { include: [srcPath], test: /\.js$/, loader: 'babel', query: { presets: ['es2015'] } }, { include: [srcPath], test: /\.js$/, loader: 'angular2-template-loader', query: { keepUrl: true } }, { include: [srcPath], test: /\.(html|css)$/, loader: 'raw', query: { minimize: true } } ] 

WebPack2不再需要这个moduleId了