classnamesplus-loader
This is a webpack loader that automatically bind css-modules to classnames.
This is a modified version of the original classnames-loader with changed behavior. I'm not sure my changes fit with the authors intent for classnames-loader as it does more than just classnames binding, so decided to fork and rename the project.
This module will bind exports to classnames, but also used with css-modules, will include the normal and module name so both are in the class list still (useful for automated tests where module based class names are not reliable)
This version also provides a mergeStyles method. This will take 2 classnames instances, and combine the classnames.
So if you have a base button stylesheet, and take that stylesheet and call .mergeStyles() with another stylesheet, the resulting stylesheet will have classes for both. See example below.
This is primarily for taking presentational components, and letting the user of the component pass in an additional style object to extend the base one with, enabling overrides.
Installation
npm install --save-dev classnamesplus-loader
API
mergeStyles
;;; const newStyles = styles;//styles.myStyle = myStyle styles_myStyle// newStyles.myStyle = myStyle styles_myStyle styles1_myStyle styles2_myStyle
importStyles
;;; styles; // styles.myStyle = myStyle styles_myStyle styles1_myStyle styles2_myStyle
Usage
To enable this loader add classnamesplus-loader
before style-loader
in webpack config:
test: /\.css$/ loader: 'classnamesplus-loader!style-loader!css-loader')
If you're using ExtractTextPlugin
your webpack config should look like this:
test: /\.css$/ loaders: 'classnamesplus-loader' ExtractTextPlugin)
Example usage in component:
;;;const cx = baseButton; // styles now have base button classes, with buttonStyles appended after it// example: cx.base = base BaseButton_base SubmitButton_base { let text = thispropsstoresubmissionInProgress ? 'Processing...' : 'Submit'; let className = ; return <button className=className>text</button>; }
You can also access the class names just as you would do that with css-modules:
;; { let text = thispropsstoresubmissionInProgress ? 'Processing...' : 'Submit'; return <button className=stylessubmitButton>text</button>; }
Sadly, babel-plugin-react-css-modules
does not appear to be using the combined class names for styleName
.
It appears it is due to that plugin resolving to the module imported directly, and not using the actual variable
in scope.
You will need to use className={cx('base', 'button')}
syntax.
To be honest, forcing that plugin to get the combined classes was a goal of this extension, but didn't work out as I had hoped.
Thanks
@itsmepetrov for original classnames-loader @JedWatson for classnames module