CSS Modules Helpers
JS Helpers for configuring CSS Modules and selecting hashed DOM selectors.
Setup
PostCSS Modules
Installnpm i --save-dev postcss-modules css-modules-helpers
Configure PostCSS Modules
require
the createManifest
module and pass it to the PostCSS Modules getJSON
option.
/* postcss.config.js */ const modules = ;const createManifest = ; module plugins: ;
Usage
Use these functions to retrieve hashed classnames and selectors from the CSS Modules output.
Note: Each of these assumes a classname manifest attached to window.cssModulesClassnames
.
getComponentClassnames
getComponentClassnames
will return all classnames associated with a given component. These values are not suitable for use in selecting elements from the DOM, but would be used to add
or remove
values from an element's classList
; const classnames = ;// { menuButton: 'site-header__menu-button___2EGUQ', menu: 'site-header__menu___9gIXs' }
getComponentSelectors
getComponentSelectors
will return all of a component's classnames formatted as DOM selectors. Use this when configuring child selectors for js-component-framework. To get only one selector from a component, see getSelectorFromComponent
.
; const selectors = ;// { menuButton: '.site-header__menu-button___2EGUQ', menu: '.site-header__menu___9gIXs' }
getElementFromComponent
getElementFromComponent
will return an element or elements from another component. By default, the function will return a single element; pass true
as a third parameter to return a NodeList.
; const element = ;// <button class="site-header__menu-button___2EGUQ"></button>
getSelectorFromComponent
getSelectorFromComponent
will return a specific selector from a component. See getComponentSelectors
to get all of a component's selectors.
; const menuButton = ;// '.site-header__menu-button___2EGUQ'