【问题标题】:How to make an Angular 2 library of components compatible with webpack.js and system.js?如何使 Angular 2 组件库与 webpack.js 和 system.js 兼容?
【发布时间】:2016-12-30 15:26:17
【问题描述】:

我正在做我的第一个 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

【问题讨论】:

    标签: angular webpack components systemjs


    【解决方案1】:

    我找到了一个基于npm包ng2-inline-require的解决方案。该工具编译scss和html外部文件,并在兼容SystemJS和Webpack的stylestemplate属性中注入代码。

    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
    

    【讨论】:

      猜你喜欢
      • 2019-10-27
      • 1970-01-01
      • 1970-01-01
      • 2018-02-02
      • 2016-05-19
      • 1970-01-01
      • 2018-06-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多