How to bundle Angular 2 component css?

2019-09-15 01:06发布

问题:

In my application for angular 1 I used to bundle all of the css in library.css and application.css. 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?

回答1:

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.



回答2:

These are the combination of the loaders that does the trick if you have

templateUrls and styleUrls

 loaders: [{
                test: /\.ts$/,
                loaders: ['awesome-typescript-loader', 'angular2-template-loader']
            },

            {
                test: /\.html$/,
                loader: 'raw-loader',
                exclude: [root('src/index.html')]
            },


            {
                test: /\.css$/,
                loader: 'to-string-loader!css-loader'
            }

        ],

and in the code

@Component({
  selector: 'my-app',
   templateUrl: 'sub.component.html',
 styleUrls: ['app.component.css']

})

export class AppComponent {

}