How to bundle Angular 2 component css?

落爺英雄遲暮 提交于 2019-12-25 08:17:53

问题


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 {

}


来源:https://stackoverflow.com/questions/40283535/how-to-bundle-angular-2-component-css

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!