在一个 angular 9 的应用程序中,应该更喜欢什么;全局样式或组件级样式

In an angular 9 app, what should be more preferred; global styles or component level styles

我们有两个选项可以在 Angular 9 应用程序中保留样式; styles.css 中的全局样式或组件 css 文件中的单个组件级样式。 如果从性能角度看项目; 什么应该是首选方式? 我们应该将所有样式保存在一个全局 style.css 文件中,还是将每个组件相关的样式保存在它们的 component.css 文件中?

有多种方法可以将全局(应用程序范围样式)样式添加到 Angular 应用程序。样式可以内联添加、在 index.html 中导入或通过 angular-cli.json 添加。 angular 允许我们在单个组件中添加组件特定样式,这将覆盖全局样式。

我认为在性能上没有太大(如果有的话)显着差异。全局或组件样式的区别在于这些样式的范围和代码库的可维护性。通常,将所有内容保留在组件中是个好主意,因为它们的范围仅限于自身,并且不会意外地覆盖其他任何地方的其他相同样式。全局样式应该主要用于主题、实用程序、助手等。

此外,您还可以选择将组件样式设置为全局样式,如果出于某种原因需要这样做的话。

迈向 define/preferable 全局样式的方式

  1. 在css文件夹中创建_base.scss文件(首先创建css文件夹)。
  2. 在 _base.scss 文件
  3. 中导入其他帮助 css 文件
  4. 在style.scss文件中添加_base scss文件的条目(style.scss在我们创建文件夹时可用)

要回答这个问题,我们必须参考 Angular official doc.

通过使用组件样式,您将拥有更好的模块化设计。

Angular can bundle component styles with components, enabling a more modular design than regular stylesheets.

但是,如果有一些样式在多个组件之间是通用的,那么最好共享一个 css,例如如果您使用 pre-processor 例如 .SCSSLESSSASS、...,您可以使用一些 _var.scss 来定义通用样式,例如 base color, fonts, ... 然后 @import 在其他组件样式中或者只在样式部分注册全局样式文件,默认情况下, 是 pre-configured 与全局 styles.css 文件。

因此,使用组件样式可为您的应用提供范围限制视图封装。此范围限制是样式模块化功能:

  • You can use the CSS class names and selectors that make the most sense in the context of each component.
  • Class names and selectors are local to the component and don't collide with classes and selectors used elsewhere in the application.
  • Changes to styles elsewhere in the application don't affect the component's styles.
  • You can co-locate the CSS code of each component with the Typescript and HTML code of the component, which leads to a neat and tidy project structure.
  • You can change or remove component CSS code without searching through the whole application to find where else the code is used.