避免在角度材质主题中使用重复的样式

问题描述

我有一个styles.theme.scss,看起来像下面的东西。

@media (prefers-color-scheme: dark) {
  @include website-theme($dark-theme);
}

@media (prefers-color-scheme: light) {
  @include website-theme($light-theme);
}

[data-theme="dark-theme"] {
  @include website-theme($dark-theme);
}

[data-theme="light-theme"] {
  @include website-theme($light-theme);
}

目标是使用prefers-color-scheme(如果由用户代理配置)。 如果在应用程序中更改主题,我还希望网站本身覆盖系统首选项。 但是,此SCSS提供警告:

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()
    stdin 29:3                                           website-theme()
    stdin 57:3                                           root stylesheet

我已经检查了提供的文档,但似乎没有涵盖这种情况,而且我不确定如何更好地构造此结构以避免重复样式。

我认为唯一可行的解​​决方案是使用JavaScript检测首选项,然后在应用程序中未配置主题的情况下设置data-theme属性

有没有比这更好的解决方案了?

我尝试过的事情:

  • 看看我是否可以像[data-theme="dark-theme"],@media (prefers-color-scheme: dark)这样将媒体查询和选择器串在一起,我认为这是不可能的。
  • 如果我可以使用SASS @if@else检查data-theme选择器是否与任何元素匹配,则包括@media查询

解决方法

今天我也发现了自己的自我战斗问题。 样式的问题是,您有两个主题:浅色和深色,以及

@include angular-material-theme('Your-Theme');

您必须提供主题(浅色或深色)。

所以您应该只覆盖一个主题,因为已经包含另一个主题 因此,如果您提供的内容较浅,则覆盖媒体查询为“暗”,反之亦然。

这是我的代码示例

@import "~@angular/material/theming";
@include mat-core();

$kyc-web-primary: mat-palette($mat-pink);
$kyc-web-accent: mat-palette($mat-pink,A200,A100,A400);
$kyc-web-warn: mat-palette($mat-red);

$kyc-web-theme-light: mat-light-theme(
  (
    color: (
      primary: $kyc-web-primary,accent: $kyc-web-accent,warn: $kyc-web-warn,),)
);

$kyc-web-theme-dark: mat-dark-theme(
  (
    color: (
      primary: $kyc-web-primary,)
);

@include angular-material-theme($kyc-web-theme-dark);


@media (prefers-color-scheme: light) {
  @include angular-material-color($kyc-web-theme-light);
}