Skip to content

Instantly share code, notes, and snippets.

@DavidWells
Last active January 22, 2020 18:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidWells/04e632a55b11c0ca53e9a8f41524d158 to your computer and use it in GitHub Desktop.
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
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!
*/
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]
}
})
}
.thing {
color: blue;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment