While CSS Modules can be used with Melody, they don't have to be used. It is up to you to decide whether you want to go down this route or not.
What are CSS Modules?
CSS Modules allow you to use CSS without relying on a global scope which can be very useful in an application setting or when you intend to create reusable components, since it avoids potential name clashes.
You can find more documentation about the concept here:
How to configure Webpack?
You can find a quick and small example of how to configure Webpack and Melody to enable CSS Modules here:
Using CSS Modules in Melody
Melody supports CSS Modules indirectly. It offers a statement that can be used to import them. However, you'll need to configure Webpack appropriately to be able to truly use them.
By using the logo as logoClass syntax you can specify a different name for the imported CSS class. This helps to avoid naming conflicts.
Use with the classes filter
When working with CSS classes, you'll often want to use the classes filter for improved ergonomics.
{% import './styles.css' as styles %}
<button type="button" class="{{ {
base: styles.button,
(styles.primary): isPrimary
} | classes }}">{{ text }}</button>
The above example will add the styles.primary class if the isPrimary property is true.
Using multiple classes
While the imported class names are just strings and can be concatenated easily (class="{{ styles.button }} {{ styles.buttonSmall }}") the ergonomics behind that are less than ideal and you'd be working around CSS modules instead of leveraging its full potential.
It is advisable to compose CSS classes within the CSS so that within the template you'll only ever need to work with one of them (unless you're dealing with modifiers like in the example above).
{% import './buttons.css' as styles %}
<button type="button" class="{{ styles.button }} {{ styles.buttonSmall }}">
Not ideal
</button>
<button type="button" class="{{ styles.secondaryButton }}">
Much better
</button>
/* the individual parts that'll make up our small button */
.button {
background: white;
}
.buttonSmall {
font-size: small;
}
/* Using CSS modules to compose them together */
.secondaryButton {
composes: button buttonSmall;
}
Both buttons will have the styles.button and the styles.buttonSmall classes but by leveraging the composes functionality offered by CSS Modules, we've been able to create a more meaningful, semantically valuable class name: styles.secondaryButton. And we've increased our separation of concern since the template no longer needs to know how such a secondary button is composed together from different CSS classes.