如何捆绑 Angular 2 个组件 css?

How to bundle Angular 2 component css?

在我的 angular 1 申请中,我曾经将 library.cssapplication.css 中的所有 css 捆绑在一起。虽然这可以用 angular 2 以与普通 css 相同的方式完成,但有一个允许 "component css" 的新功能。据我所知,Angular 只是下载 css 文件,然后对其进行处理以添加一些 id,以免相互干扰。

现在,如果我将所有这些 css 和 Angular 捆绑在一起,我将无法找到它们。是否有可能对组件 css 进行捆绑?也许存在与捆绑 HTML 类似的方法,其中 HTML 确实作为字符串放入 .js?

我设法通过 webpack 和一个特殊的 angular2-template-loader plugin 实现了这一点。这是来自 webpack 2 的配置:

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

基本上它的作用是,它将 templateUrlstyleUrls 替换为内联 templatestyles,并将它们作为单独的 "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。整个设置可以在 Anagular tutorial.

中找到

如果您有

,这些是加载程序的组合,可以解决问题

templateUrlsstyleUrls

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

        ],

在代码中

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

})

export class AppComponent {

}