bem-classnames-loader for webpack
This loader extracts modifiers and states defined in your css files and then provide an interface for generating class names. So you get a something similar with css-modules but with BEM.
Installation
npm install bem-classnames-loader --save-dev
Examples
button.scss
.button
button.js
; // button // button is-disabled // button button--borderless // button is-disabled button--type-success // button is-disabled form__button // button is-disabled button--type-default form__button // button // button__inner // button__inner
webpack.config.js
...// Optional parameters (you can pass them with loader query too)bemClassnames: prefixes: state: 'is-' module: loaders: test: /\.scss$/ loader: 'bem-classnames!style!css!sass' // If you using extract-text-plugin // loaders: ['bem-classnames', ExtractTextPlugin.extract('css!sass')] ...
React component example
This example shows how easy you can use props to generate class names.
;; static propTypes = disabled: PropTypesbool borderless: PropTypesbool type: PropTypes; ; static defaultProps = type: 'default' ; { return <button className=> <div className=> Click me </div> </button> ; } ;
Now render Button
with different props:
<Button /> //button button--type-default<Button borderless /> //button button--type-default button--borderless<Button type="success" /> //button button--type-success<Button type="success" disabled /> //button button--type-success is-disabled
Loader options
prefixes: element: '__' modifier: '--' state: 'is-' modifierValue: '-' stateValue: '-' applyClassPrefix: ''
prefixes
- define bem entity prefixesapplyClassPrefix
- prefix will be added to class names. For example, you usepostcss-loader
and it'spostcss-class-prefix
plugin to add prefixes in your css. So you should useapplyClassPrefix
to add prefixes on Javascript side.
API
;
style
Itself is a function, which generates class names in cool way.
style.ns
Get/set namespace. Sometimes class name is very large, namespaces help you to write lesser code.
Example:
// button // button__inner // Set new namespace if you needstyle; // super-good-component // super-good-component__placeholder
style.modifier
Adds new modifier.
Example:
// Add boolean modifierstyle; // button button--fade // Add string modifierstyle; // button button--size-sm
style.state
Adds new state.
Example:
// Add boolean statestyle; // button is-active // Add string statestyle; // button is-foo-bar
style.getClasses
Returns defined classes.