You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 15主题构建:如何避免排版样式重复警告?

解决Angular 15多主题下公共样式重复的警告

问题场景

按照教程及Angular官方文档编写的Angular 15主题SCSS代码如下:

//======================================
// SHARED THEME STYLES
//======================================
@include mat.core();
.dark-theme {
    //======================================
    // THEME INITIALIZATION
    //======================================
    @include mat.core-theme($theme);
    @include mat.all-component-themes($theme);
}
.light-theme {
    //======================================
    // THEME INITIALIZATION
    //======================================
    @include mat.core-theme($theme);
    @include mat.all-component-themes($theme);
}

执行构建时收到重复样式警告:

./projects/playground/src/styles.scss - Warning: Module Warning (from ./node_modules/sass-loader/dist/cjs.js):
The same typography styles are generated multiple times. Read more about how style duplication can be avoided in a dedicated guide. https://github.com/angular/components/blob/main/guides/duplicate-theming-styles.md

../../../../node_modules/@angular/material/core/theming/_theming.scss 360:7  private-check-duplicate-theme-styles()
../../../../node_modules/@angular/material/core/_core-theme.scss 77:3        theme()
../../../elytra/src/lib/styles/themes/dark-theme.scss 139:5                  @use
../styles.scss 9:1  

解决方案

问题根源在于mat.core-theme()和mat.all-component-themes()同时包含公共基础样式(如排版、组件结构)和主题差异化样式(如颜色、主题变量),多次调用会重复生成公共部分代码。只需拆分公共样式与主题差异化样式,公共部分全局仅调用一次,主题类中只加载主题相关样式:

修改后的代码

//======================================
// 全局公共基础样式(仅调用一次)
//======================================
@include mat.core();
// 加载所有组件的基础结构样式(不含主题色)
@include mat.all-component-base-themes();

//======================================
// 主题差异化样式
//======================================
.dark-theme {
    // 仅加载核心主题颜色配置
    @include mat.core-color($theme);
    // 加载所有组件的主题颜色样式
    @include mat.all-component-color-themes($theme);
}

.light-theme {
    @include mat.core-color($theme);
    @include mat.all-component-color-themes($theme);
}

原理说明

  • mat.core() + mat.all-component-base-themes():全局一次性加载所有公共基础样式(如排版、组件默认结构),不会随主题变化。
  • mat.core-color() + mat.all-component-color-themes():仅在主题类中加载与主题相关的颜色、变量配置,避免重复生成公共代码。

内容的提问来源于stack exchange,提问作者Ole

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 21:25:24