首页 > 解决方案 > 为什么将类移动到 Angular 中的共享 css 文件会增加包大小

问题描述

这是针对 Angular 11 应用程序的。我有一个共享的 css 文件,我包含在几个组件中,如下所示:

@Component({
  selector: 'app-my-x-selector',
  templateUrl: './my-component-x.html',
  styleUrls: ['component-x.css', 'shared.css']
})

将以下测试类添加到组件的 css 文件之一会使包大小增加 61 个字节,这与添加的源代码片段的大小相匹配。但是将类移动到共享 css 会使包大小增加 140 个字节。为什么?看起来 Angular 有效地为每个组件克隆了包含共享 css 文件的类,这严重限制了共享 css 的目的,如果不是的话。

.tr-test00 {
    display: block;
    margin-left: 45rem;
    padding-left: 3rem;
}

标签: cssangularbundle

解决方案


@Ya,想象一下,您有两个简单的组件,其中包含 .css 之类的

  //component-one
  template: `<h1>Hello</h1>`,
  styles: [`h1 { color:blue }`]

  //component-two
  template: `<h1>By</h1>`,
  styles: [`h1 { color:red }`]

Angular 制作了一个独特的捆绑包,类似于

h1[_ngcontent-edf-c40] {
    color: green;
}
h1[_ngcontent-edf-c41] {
  color: red;
}

并创建一个 .html 之类的

<hello _ngcontent-bwn-c39="">
  <h1 _ngcontent-edf-c40="">Hello</h1> //<--this is the component one
</hello>

<other_ngcontent-bwn-c42="">
   <h1 _ngcontent-edf-c41="">By</h1> //<--this is the component two
</other>

这使得在组件一中您看到 h1 绿色,而在组件二中看到 h1 红色

当您将一个通用的 .css 引用到两个不同的组件时,Angular 会生成一个类似

h1[_ngcontent-edf-c40] {
    color: green;
}
h1[_ngcontent-edf-c41] {
  color: green;
}

.html 又是

<hello _ngcontent-bwn-c39>
   <h1 _ngcontent-edf-c40>Hello</h1> //<--this is the component one
</hello>

<other _ngcontent-bwn-c48>
   <h1 _ngcontent-edf-c41>By</h1> //<--this is the component two
</other>

这是因为bunlde增加了两倍的原因。如果您愿意,您可以采用另一种方法,即使用通用 .css 并以这种方式添加您的 angular.json

.common h1{
   color:green
}

并将你的组件包含在一个 div 中

<div class="common">
    <h1>Hello</h1>
</div>

<div class="common">
    <h1>By</h1>
</div>

.html 它看起来像

   <hello _ngcontent-jxl-c46="">
      <div class="common">
         <h1>Hello</h1>
      </div>
   </hello>

   <other _ngcontent-jxl-c46="">
       <div class="common">
          <h1>By</h1>
       </div>
    </other>

推荐阅读