Last active
January 22, 2020 18:02
-
-
Save DavidWells/04e632a55b11c0ca53e9a8f41524d158 to your computer and use it in GitHub Desktop.
Use proxies in dev to guard against potentially missing styles. Also use linting & stuff for warning etc. This is handy for ensuring style refactors don't result in undefined class names. Now a package https://www.npmjs.com/package/style-guard
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 React from "react" | |
import { Link } from "react-router-dom" | |
import styleGuard from './style-guard' | |
import css from './styles.css' | |
const styles = styleGuard(css) | |
export default function NavBar(props) { | |
const { auth, handleLogout } = props | |
return ( | |
<div className={styles.thing}> | |
<span className={styles.doesNotExist}></span> | |
</div> | |
) | |
} | |
/* | |
styles.doesNotExist will cause a dev error because its missing or has been removed! | |
*/ |
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
export default function styleGuard(styles) { | |
if (process.env.NODE_ENV !== 'development') { | |
return styles | |
} | |
return new Proxy(styles, { | |
get: (obj, prop, receiver) => { | |
if (!obj || typeof obj !== 'object') { | |
throw new Error('No styles found or styles is not object') | |
} | |
if (!obj[prop]) { | |
const firstKey = Object.keys(obj)[0] | |
const componentName = (obj[firstKey] || '').replace(/(__.*)/, '') | |
throw new Error(`Styles error class "${prop}" does not exist in ${componentName}`) | |
} | |
return obj[prop] | |
} | |
}) | |
} |
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
.thing { | |
color: blue; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment