PostCSS Register Property lets you register properties in CSS.
@property --highlight-color {
inherits: true;
initial-value: red;
syntax: "<color>";
}
@property --gap-spacing {
inherits: false;
initial-value: 1em;
syntax: "<length-percentage>";
}
These properties are transformed into JSON.
[
{
"name": "--highlight-color",
"inherits": true,
"initialValue": "red",
"syntax": "<color>"
},
{
"name": "--gap-spacing",
"initialValue": "1em",
"syntax": "<length-percentage>"
}
]
These properties can be imported and registered in a browser.
import properties from './styles.css.properties.json';
if (window.CSS && CSS.registerProperty) {
for (const descriptor of properties) {
CSS.registerProperty(descriptor);
}
}
Optionally, you can even detect registrations from custom properties:
:root {
--some-border: 5px solid rebeccapurple;
--some-image: url("image.webp");
--some-transform: scale(1.25, 1.25);
}
[
{
"name": "--some-border",
"syntax": "<length> <custom-ident> <color>"
},
{
"name": "--some-image",
"syntax": "<image>"
},
{
"name": "--some-transform",
"syntax": "<transform-function>"
}
]
Add PostCSS Register Property to your project:
npm install postcss-register-property --save-dev
Use PostCSS Register Property to process your CSS:
const postcssRegisterProperty = require('postcss-register-property');
postcssRegisterProperty.process(YOUR_CSS /*, processOptions, pluginOptions */);
Or use it as a PostCSS plugin:
const postcss = require('postcss');
const postcssRegisterProperty = require('postcss-register-property');
postcss([
postcssRegisterProperty(/* pluginOptions */)
]).process(YOUR_CSS /*, processOptions */);
PostCSS Register Property runs in all Node environments, with special instructions for:
Node | PostCSS CLI | Webpack | Create React App | Gulp | Grunt |
---|
The detect
option determines whether registrations will be detected from
Custom Properties. By default, they are not detected.
postcssRegisterProperty({ detect: true }) // detect custom property registrations
The getJSON
option defines the function that handles all of the collected
properties from CSS. If not specified, these properties will be written as JSON
to a file determined by the to
option.
If specified, the getJSON
function is passed 3 arguments; the path to the
source CSS, an object of all the collected properties, and the path to the
destination JSON. Asynchronous functions should return promise-like values.
postcssRegisterProperty({
getJSON(cssFileName, properties, jsonFileName) {
/* do something with cssFileName, properties, and jsonFileName */
}
)
The to
option determines the destination path where the properties will be
written to as JSON. If not specified, the destination will be the input source
filename appended with .properties.json
.