unique.macro
v1.0.1
Published
> Create unique and deterministic strings with a babel macro
Downloads
22
Readme
unqiue.macro
Create unique and deterministic strings with a babel macro
unique.macro is a babel macro that generates a unique string based on filename to the nearest package.json, the name in the nearest package.json and the contents of the file it's in. unique.macro is primarily useful for generating unique class names to use as selectors with css-in-js libraries like emotion or glamor. Using unique.macro is better for Server Side Rendering than Math.random or something like it because it will use the same class on the server as on the client so there won't be any mismatches.
Install
yarn add --dev babel-macros unique.macroor
npm install --save-dev babel-macros unique.macroConfiguration
unique.macro requires babel-macros to be in your babel config as below.
Via .babelrc (Recommended)
.babelrc
{
"plugins": ["babel-macros"]
}Via CLI
babel --plugins babel-macros script.jsVia Node API
require('babel-core').transform('code', {
plugins: ['babel-macros'],
})Use
import unique from 'unique.macro'
const uniqueString = unique()
// use it with a css-in-js library like emotion
import { css } from 'emotion'
const classWithStyles = css`
background-color: green;
.${uniqueString} {
background-color: hotpink;
}
`
<div className={classWithStyles}>
some text with a green background
<span className={uniqueString}>some text with a hotpink background</span>
</div>
Prefix
By default the unique hash generated by babel-macros is prefixed with css- so that it can be used with jest-glamor-react in snapshots and be replaced with glamor-{index}. The prefix can be changed in two ways.
Inline
import unique from 'unique.macro'
const someClass = unique('some-other-prefix-')
// note the string MUST be inline, e.g. this won't work
const customPrefix = 'another-prefix-'
const throwsAnError = unique(customPrefix)Config File
unique.macro also supports changing the prefix with babel-macros' config. If there is an inline prefix it will be used instead of the config file. babel-macros supports configuration via cosmiconfig so it can be configured with any of the ways below.
.babel-macrosrc.babel-macrosrc.json.babel-macrosrc.yaml.babel-macrosrc.yml.babel-macrosrc.jsbabel-macros.config.jsbabelMacrosinpackage.json
Example .babel-macrosrc.json
{
"unique": {
"prefix": "some-other-prefix-"
}
}Thanks
Thanks to the styled-components team for writing the code to generate the unique hash.
LICENSE
MIT
