@pugpigbolt/style-transform
v0.1.4
Published
Converts CSS custom property declarations into scoped CSS rules. Works against variables already on `:root`, inline `<style>` elements, or external `<link>` stylesheets including ones that load after your bundle.
Readme
@pugpigbolt/style-transform
Converts CSS custom property declarations into scoped CSS rules. Works against variables already on :root, inline <style> elements, or external <link> stylesheets including ones that load after your bundle.
Installation
npm install @pugpigbolt/style-transformUsage
Define theme variables in a stylesheet:
:root {
--my-style-component-element-color: #1a1a1a;
--my-style-component-card-element-fontSize: 1.2rem;
}Register the transformer once at init:
import { createCssVarTransformer, registerCssVars } from '@pugpigbolt/style-transform'
const transformer = createCssVarTransformer({
prefix: '--my-style',
buildSelector(segments) {
const [component, ...rest] = segments
return `.${component} .${rest.join('-')}`
},
})
const dispose = registerCssVars('[data-theme]', transformer, (css) => {
const el = document.createElement('style')
el.textContent = css
document.head.appendChild(el)
})Any matching <style> element - already in the DOM or arriving later - gets transformed into scoped rules. Call dispose() to stop watching.
CSS variable encoding
Variables follow the pattern --{prefix}-{...selectorSegments}-{camelCasedProperty}:
| Segments | Generated selector |
| -------- | ----------------------------- |
| 1 | .element |
| 2 | .component .element |
| 3+ | .component.variant .element |
Property names are camelCase-aware: backgroundColor → background-color.
API
registerCssVars(selectorOrPattern, transformer, onCss, options?)
Accepts a CSS selector string, an array of selectors, or a RegExp href pattern for <link> stylesheets. Returns a disposer.
const dispose = registerCssVars('[data-theme]', transformer, onCss)
const dispose = registerCssVars(['[data-theme]', '#theme-overrides'], transformer, onCss)
const dispose = registerCssVars(/\/themes\/\w+\.css$/, transformer, onCss)
dispose()createCssVarTransformer(config)
Creates a transformer for a custom prefix and selector convention.
import { createCssVarTransformer, camelToKebab } from '@pugpigbolt/style-transform'
const transformer = createCssVarTransformer({
prefix: '--my-style',
buildSelector(segments) {
const [component, ...rest] = segments
return `.${camelToKebab(component)} .${rest.map(camelToKebab).join('-')}`
},
})Default transformers
The package ships with pre-built transformers for common conventions. Import them directly if they match your use case.
