简体   繁体   中英

How to create multiple themes in sass unsing sass modules feature?

Before modules were introduced to sass, you could make a themed stylesheet this way:

themeDark.scss:

$color: black;

baseButton.scss:

button {
  color: $color;
}

button.scss:

@import './_themeDark.scss'
@import './_baseButton.scss'

Now, modules were introduced to sass and @import is getting deprecated. How to achieve the same effect using sass modules?

Im looking for a solution, where some files are used as partial stylesheets. In the main file they are combined to form a final stylesheet that will be imported.

What i have tried:

  • use @use instead of @import . It does not work, because variables from other modules are not seen.
  • use mixins. The problem is that you have to pass all the variables through arguments and it is much harder to maintain than the solution above with @import .

You can have scss map to store all themes

$themes: (
  theme1: (color: red),
  theme2: (color: orange),
  theme3: (color: yellow),
  theme4: (color: green),
  theme5: (color: blue)
);

Using this map is with an @each loop.

@each $theme, $map in $themes {
  .#{$theme} {
    color: map-get($map, color);
  }
}

On each loop, assign these values to $theme and $map respectively.

$theme - Theme name $map - Map of all theme variables

You now use the map-get() function to get any theme variable from $map and output the correct property for each theme.

@each $theme, $map in $themes {
  .#{$theme} & { // <--- Notice the & here!
    color: map-get($map, color);
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM