Sass Modules are a feature in the Sass CSS preprocessor that allow you to create reusable and modular CSS components. They help in organizing your CSS code, reducing duplication, and promoting maintainability.
To use Sass Modules, you need to have Sass installed in your project. You can install it using Node.js or through Ruby Gem.
Here, we will use the Node.js method:
npm install -D sassA Sass module is defined by a file with a .scm.scss extension (.scm stands for Sass module). Let's create a simple module for buttons:
// _buttons.scm.scss
$button-primary-color: red;
$button-secondary-color: blue;
.button {
&--primary {
color: $button-primary-color;
}
&--secondary {
color: $button-secondary-color;
}
}In this example, we have created a module for buttons with primary and secondary styles.
To use the module in your main CSS file, you import it like this:
// style.scss
@use 'buttons' as btn;
.my-button {
@extend .btn--primary;
}In the above example, we have imported the buttons module and extended the .my-button class with the primary button styles.
You can nest modules within other modules for more organized and structured code.
// _buttons.scm.scss
$button-primary-color: red;
$button-secondary-color: blue;
@module button-styles
.button {
&--primary {
color: $button-primary-color;
}
&--secondary {
color: $button-secondary-color;
}
}
@end
@module button-components
@import 'button-styles';
.my-button {
@extend .button--primary;
}
@endIn this example, we have nested the button-components module within the button-styles module.
Partial modules are regular Sass files without the .scm extension. They can be imported into modules or main CSS files.
// _button-utils.scss
.button-centered {
text-align: center;
}// _buttons.scm.scss
@import 'button-utils';
@module button-styles
// ...
.button {
@extend .button-centered;
}
@endWhat is the purpose of Sass Modules?
Sass Modules are a powerful feature that can greatly improve your CSS organization and maintainability. By creating reusable and modular components, you can write less code, reduce duplication, and maintain a clean, organized project structure.
Happy coding! 💻🎉