Ilya Chernomordik Ilya Chernomordik - 1 year ago 127
CSS Question

How to bundle Angular 2 component css?

In my application for angular 1 I used to bundle all of the css in

. While this can be done with angular 2 the same way for ordinary css, there is a new feature that allows a "component css". As far as I can see Angular just downloads the css file and then processes it to add some id's to not interfere with each other.

Now if I just bundle all of these css'es Angular just won't be able to find them. Is it possible at all to do bundling of component css? Perhaps a similar way to bundling HTML exists, where HTML is really put into .js as string?

Answer Source

I managed to achieve this with webpack and a special angular2-template-loader plugin. This is the config from webpack 2:

module: {
   rules: [
      test: /\.ts$/,
      use: ['awesome-typescript-loader', 'angular2-template-loader']

Basically what it does, it replaces templateUrl and styleUrls with inline template and styles and just stores them in a string as a separate "module".

How does it work

The angular2-template-loader searches for templateUrl and styleUrls declarations inside of the Angular 2 Component metadata and replaces the paths with the corresponding require statement. If keepUrl=true is added to the loader's query string, templateUrl and styleUrls will not be replaced by template and style respectively so you can use a loader like file-loader.

The generated require statements will be handled by the given loader for .html and .js files.

P.S. The whole set up can be found in Anagular tutorial.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download