Last active
October 7, 2018 16:50
-
-
Save davidbarral/2414e504cef150e92c4b1482daa87f1b to your computer and use it in GitHub Desktop.
Module mapper and custom toJson for bemified CSS modules (see https://medium.com/trabe/using-bem-conventions-in-css-modules-leveraging-custom-webpack-loaders-fd985f72bcb2)
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
const hyphenize = s => s.replace(/([A-Z])/g, g => `-${g[0].toLowerCase()}`); | |
const classify = (block, element, modifier) => { | |
const parts = [hyphenize(block)]; | |
if (element) { | |
parts.push("__"); | |
parts.push(hyphenize(element)); | |
} | |
if (modifier) { | |
parts.push("--"); | |
parts.push(hyphenize(modifier.slice(1))); | |
} | |
return parts.join(""); | |
}; | |
const blockProxy = block => | |
new Proxy( | |
{ cssModule: true }, | |
{ | |
get: (target, key) => { | |
if (key === "hasOwnProperty") { | |
return prop => prop === "toString"; | |
} | |
if (key === "toString" || key === Symbol.toPrimitive) { | |
return () => classify(block); | |
} | |
if (key.match(/^\$/)) { | |
const modifier = key; | |
return modifierProxy(block, undefined, modifier); | |
} | |
const element = key; | |
return elementProxy(block, element); | |
}, | |
}, | |
); | |
const elementProxy = (block, element) => | |
new Proxy( | |
{ cssModule: true }, | |
{ | |
get: (target, key) => { | |
if (key === "hasOwnProperty") { | |
return prop => prop === "toString"; | |
} | |
if (key === "toString" || key === Symbol.toPrimitive) { | |
return () => classify(block, element); | |
} | |
const modifier = key; | |
return modifierProxy(block, element, modifier); | |
}, | |
}, | |
); | |
const modifierProxy = (block, element, modifier) => ({ | |
cssModule: true, | |
toString: () => classify(block, element, modifier), | |
}); | |
export default new Proxy( | |
{}, | |
{ | |
get: (_, block) => blockProxy(block), | |
}, | |
); |
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
import enzymeToJons from "enzyme-to-json"; | |
const fixCSSmodules = info => { | |
if (info.props && info.props.className && info.props.className.cssModule) { | |
info.props.className = info.props.className.toString(); | |
} | |
return info; | |
}; | |
export const toJson = (wrapper, options) => | |
enzymeToJson(wrapper, { | |
map: fixCSSmodules, | |
...options, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment