如何使 Angular 2 组件库与 webpack.js 和 system.js 兼容?
How to make an Angular 2 library of components compatible with webpack.js and system.js?
我正在做我的第一个 Angular 2 库。目前,它只是一个组件库。我想要一个与 Webpack 和 SystemJS 兼容的库。我设法用与 SystemJs 兼容的代码编写了第一个组件,并重写了代码以与 Webpack 兼容,但哪个是强制它与两者兼容的正确代码?
import {Component} from '@angular/core';
@Component({
selector: 'foo',
moduleId: typeof module.id == "string" ? module.id : null,
templateUrl: 'foo.component.html',
styleUrls: ['foo.component.css']
})
export class FooComponent {
logo: String;
name: String;
constructor() {
this.logo = '';
this.name = 'My name';
}
}
目前我发现this trick可以解决部分相对路径问题。这适用于 systemJS,但我在使用 Webpack 的项目中仍然遇到此错误:
Cannot GET /application.component.html
Unhandled Promise rejection: Failed to load foo.component.html ; Zone: <root> ; Task: Promise.then ; Value: Failed to load foo.component.html undefined
Error: Uncaught (in promise): Failed to load foo.component.html
我找到了一个基于 npm 包的解决方案 ng2-inline-require。该工具编译scss和html外部文件并将代码注入styles和template属性中,这些属性与SystemJS和Webpack兼容。
import {Component} from '@angular/core';
@Component({
selector: 'foo',
moduleId: typeof module.id == "string" ? module.id : null,
template: require('./foo.component.html'),
styles: [ require('./foo.component.css') ]
})
export class FooComponent {
logo: String;
name: String;
constructor() {
this.logo = '';
this.name = 'My name';
}
}
并像这样编译它:
ng2-inline-require -i ./src/foo.component.ts -o ./dist/foo.component.ts
我正在做我的第一个 Angular 2 库。目前,它只是一个组件库。我想要一个与 Webpack 和 SystemJS 兼容的库。我设法用与 SystemJs 兼容的代码编写了第一个组件,并重写了代码以与 Webpack 兼容,但哪个是强制它与两者兼容的正确代码?
import {Component} from '@angular/core';
@Component({
selector: 'foo',
moduleId: typeof module.id == "string" ? module.id : null,
templateUrl: 'foo.component.html',
styleUrls: ['foo.component.css']
})
export class FooComponent {
logo: String;
name: String;
constructor() {
this.logo = '';
this.name = 'My name';
}
}
目前我发现this trick可以解决部分相对路径问题。这适用于 systemJS,但我在使用 Webpack 的项目中仍然遇到此错误:
Cannot GET /application.component.html
Unhandled Promise rejection: Failed to load foo.component.html ; Zone: <root> ; Task: Promise.then ; Value: Failed to load foo.component.html undefined
Error: Uncaught (in promise): Failed to load foo.component.html
我找到了一个基于 npm 包的解决方案 ng2-inline-require。该工具编译scss和html外部文件并将代码注入styles和template属性中,这些属性与SystemJS和Webpack兼容。
import {Component} from '@angular/core';
@Component({
selector: 'foo',
moduleId: typeof module.id == "string" ? module.id : null,
template: require('./foo.component.html'),
styles: [ require('./foo.component.css') ]
})
export class FooComponent {
logo: String;
name: String;
constructor() {
this.logo = '';
this.name = 'My name';
}
}
并像这样编译它:
ng2-inline-require -i ./src/foo.component.ts -o ./dist/foo.component.ts