Search code examples
javascriptangularsassangular-materialangular-theming

Generating an Angular Theme for Angular 15?


In the various tutorials I've seen themes generated like this:

//======================================
// 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);
}

If I understand it correctly, this is also how Angular's Documentation tells us to do it. However when I run the build I get these warnings.

./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  

How do we create the themes without duplicating commons styles like Typography?


Solution

  • According to their documentation https://material.angular.io/guide/theming#multiple-themes-in-one-file

    You will see that when defining two themes you should make use of the core-color for all themes aside from the primary.

    A more thorough explanation can also be found in their docs https://material.angular.io/guide/duplicate-theming-styles

    The primary concept is the *-theme mixins apply the entirety of the theme (aka duplicating it each time *-theme is called) whereas the *-color mixins only change the color of the respective components while leaving the rest alone.

    I made changes to your example below to reflect the reading.

    //Say this is your primary 
    .dark-theme {
        //======================================
        // THEME INITIALIZATION
        //======================================
        @include mat.core-theme($theme);
        @include mat.all-component-themes($theme);
    }
    //and this being your secondary theme
    .light-theme {
        //======================================
        // THEME INITIALIZATION
        //======================================
        @include mat.core-color($theme);  <---- This is the magic
        @include mat.all-component-colors($theme); <---- This is the magic
    }