Search code examples
angularwebpackcomponentssystemjs

How to make an Angular 2 library of components compatible with webpack.js and system.js?


I'm doing my first Angular 2 library. For the moment, it's just a library of components. I would like a library compatible with Webpack and SystemJS. I managed to write a first component with a code compatible with SystemJs and rewrite the code to be compatible with Webpack but which is the right code to force it to be compatible with both ?

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';
 }
}

For the moment I found this trick to resolve a part of the relative path problem. That works with systemJS but I have still this error with a project using 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

Solution

  • I found a solution based on the npm package ng2-inline-require. This tool compile scss and html external files and inject the code in the styles and template attributes which are compatible with SystemJS and 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';
     }
    }
    

    and compile it like this :

    ng2-inline-require -i ./src/foo.component.ts -o ./dist/foo.component.ts