Can I use css-modules with LESS + nesting?

mpen picture mpen · Oct 31, 2015 · Viewed 11.9k times · Source

The documentation on css-modules is pretty sparse, so I'm not sure if I can do this or not.

This article says the way I'd style a button with normal and error states would look like this:

.common { /* font-sizes, padding, border-radius */ }
.normal { composes: common; /* blue color, light blue background */ }
.error { composes: common; /* red color, light red background */ }

But I'd prefer to write it like this:

.common {
    /* font-sizes, padding, border-radius */
    &.normal { /* blue color, light blue background */ }
    &.error { /* red color, light red background */ }
}

Like I've always done, without introducing this new composes syntax. I think it's more clear which styles build on top of other styles if I can actually nest them in code.

But I don't know what this would be exported as by css-modules? The only examples they give are simple class name selectors. I have no idea what about .common.normal will be exported as, or what .common > .normal ~ .strange? Do I basically have to not use any kind of CSS selector if I use css-modules?

Answer

Jason Peng picture Jason Peng · Jan 6, 2017
.common {
    /* font-sizes, padding, border-radius */
    :global {
        &.normal { /* blue color, light blue background */ }
        &.error { /* red color, light red background */ }
    }
}

That's my solution. If you use styles.common, the css will be:

.ramdomStrings {
    /* I'm not sure if this exists, but it doesn't matter */
}
.ramdomStrings.normal { /* blue color, light blue background */ }
.randomStrings.error { /* red color, light red background */ }