首页 > 解决方案 > 如何在角度不多次生成相同的颜色样式?

问题描述

在 Angular 中,我生成了一个自定义主题文件、一个根样式文件,并且我的所有组件都有自己的自定义样式文件。但是,由于我更新到版本 10,我的终端被警告发送垃圾邮件

WARNING: The same color styles are generated multiple times. Read more about how style duplication can be avoided in a dedicated guide. https://github.com/angular/components/blob/master/guides/duplicate-theming-styles.md
    node_modules/@angular/material/_theming.scss 1648:7  -mat-check-duplicate-theme-styles()
    node_modules/@angular/material/_theming.scss 7010:3  angular-material-theme()
    node_modules/@angular/material/_theming.scss 7061:3  angular-material-color()
    src/_custom_theme.scss 242:3                         @import
    stdin 2:9        

按照指南,我可以将此错误减少到至少四个到达。此错误列出了我的 node_modules 中的 custom_theme 文件和 @angular/material。我真的很想知道我做错了什么导致这个错误。在我的 custom_theme 的第 242 行,我正在生成我的深色主题.custom-dark-theme { @include angular-material-color($app-theme-dark); }

标签: angularsassangular-material

解决方案


一般要做的事情是避免您的组件 sccs @import-ing 一个文件,该文件本身就是@include材料核心 mixin 之一。因此,您可以在部分中定义主题和一些可共享的主题常量/混合,然后在导入主题定义的全局样式中创建样式。更明确地说:

  • 创建一个类似 的文件_my-theme.scss,前导下划线使其成为 sass 部分。
  • 在该文件中,仅通过调用材质的函数来定义主题。请注意,这只是一个函数,它只是创建一个大的 Sass 贴图,材质库的其余部分使用它来实际生成样式。它本身并不像 mixins 那样“生成”样式。material-light-theme
  • 在全局/根样式文件中,导入'my-theme',然后@include是颜色/样式混合。
  • 在您的组件文件中,仅从我的自定义主题部分导入,而不是从根文件导入

但是,对于 Sass 和 Angular 12 的更新版本,更好的方法是使用更好地处理这些部分文件中“共享”公共代码@import的语法,而不是使用 . @use简单示例/入门代码

_my-theme.scss

@use "~@angular/material" as mat;

$my-theme-dark: mat.define-dark-theme(
  // stuff here
);

styles.scss


@use "~@angular/material" as mat;
@use './my-theme' as my-theme;

@include mat.core()

// general style defaults

.app-dark {
  @include mat.all-component-colors(my-theme.$my-theme-dark);
}

some-component.scss


@use "~@angular/material" as mat;
@use 'my-theme' as my-theme;

// do anything with mat and your definitions from my-theme

推荐阅读