Save some bytes when using multiple themes in angular material components

ยท

1 min read

Save some bytes when using multiple themes in angular material components

Let's say you have a theme file called dark.scss like below.

// src/styles/themes/dark.scss

@use "sass:map";
@use "@angular/material" as mat;

@use "../typography/config" as typography;
@use "../components";

$my-app-dark-primary: mat.define-palette(mat.$blue-grey-palette);
$my-app-dark-accent: mat.define-palette(mat.$amber-palette, A200, A100, A400);
$my-app-dark-warn: mat.define-palette(mat.$deep-orange-palette);
$my-app-dark-theme: mat.define-dark-theme(
  (
    color: (
      primary: $my-app-dark-primary,
      accent: $my-app-dark-accent,
      warn: $my-app-dark-warn,
    ),
  )
);

.dark-theme {
  @include mat.core-color($my-app-dark-theme);
  @include mat.button-color($my-app-dark-theme);
}

} Now, in your assets array in angular.json, just exclude the dark theme file, see below code for example. With below code, dark theme file will be bundled as dark-theme.css in final output.

"styles": [
              "src/styles.scss",
              {
                "input": "src/styles/themes/dark.scss",
                "bundleName": "dark-theme",
                "inject": false
              }
            ],

Now, in your index.html, load dark-theme.css whenever required:

<link rel="stylesheet" href="dark-theme.css">

That's all! To know more, visit and read the full article now: