lukeed / clsx

A tiny (239B) utility for constructing `className` strings conditionally.
MIT License
8.28k stars 143 forks source link

CSS modules support #19

Closed migueljteixeira closed 4 years ago

migueljteixeira commented 4 years ago

Hi Luke! Excellent job with this module! 🥇

One question: Is it possible to make it work with CSS modules? Similar to what classnames does (https://github.com/JedWatson/classnames#alternate-bind-version-for-css-modules).

Thank you

lukeed commented 4 years ago

Hey, thanks :)

There's actually no reason to have that mode for CSS modules. All PostCSS and/or CSS-loader-type integrations with Rollup/webpack will automatically include a styles object for you, and you can reference it directly.

In code:

import clsx from 'clsx';
import style from './index.css';

export default function Button(props) {
  let cls = clsx('btn', props.sm && style.small, props.outline && style.outline);
  return <button className={ cls }>{ props.label }</button>;
}

... will just work. Once any of those PostCSS/CSS loaders run, the above component is (effectively) turned into:

import clsx from 'clsx';
var style = { small: 'ahgs', outline: 'zjh1' }; //<~ here

export default function Button(props) {
  let cls = clsx('btn', props.sm && style.small, props.outline && style.outline);
  return <button className={ cls }>{ props.label }</button>;
}

This is the same as the link you've shared.

If I'm missing something, please let me know. Thanks!