Last active
November 6, 2022 09:18
-
-
Save gordonbrander/1d6bf6413dc4724a7739 to your computer and use it in GitHub Desktop.
CSS namespacing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Automatically namespace all CSS selectors. | |
Eliminates most problems with style leak | |
.active {} | |
...becomes | |
.button-active {} | |
*/ | |
const CLASS_SELECTOR = /\.(\w+)/; | |
const ID_SELECTOR = /\#(\w+)/; | |
const WHITESPACE = /^\s+$/; | |
const SELECTOR = /^[.#]/; | |
const prefixClasses = (css, prefix) => | |
css.replace(CLASS_SELECTOR, '.' + prefix + '$1'); | |
const prefixIds = (css, prefix) => | |
css.replace(ID_SELECTOR, '#' + prefix + '$1'); | |
export const namespace = (css, ns) => | |
prefixClasses(prefixIds(css, ns), ns); | |
const isLineValid = (line) => WHITESPACE.test(line) || SELECTOR.test(line); | |
const removeExt = (path) => path.replace(/\.\w+$/, ''); | |
const namespaceFromPath = (path) => | |
removeExt(path.replace(/^\//, '').replace('/', '-')) + '-'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment