PostCSS Custom Properties
PostCSS Custom Properties lets you use Custom Properties in CSS, following
the CSS Custom Properties specification.
:root {
--color: red;
}
h1 {
color: var(--color);
}
/* becomes */
:root {
--color: red;
}
h1 {
color: red;
color: var(--color);
}
Usage
Add PostCSS Custom Properties to your project:
npm install postcss-custom-properties --save-dev
Use PostCSS Custom Properties to process your CSS:
const postcssCustomProperties = require('postcss-custom-properties');
postcssCustomProperties.process(YOUR_CSS );
Or use it as a PostCSS plugin:
const postcss = require('postcss');
const postcssCustomProperties = require('postcss-custom-properties');
postcss([
postcssCustomProperties()
]).process(YOUR_CSS );
PostCSS Custom Properties runs in all Node environments, with special instructions for:
Options
preserve
The preserve
option determines whether Custom Properties and properties using
custom properties should be preserved in their original form. By default, both
of these are preserved.
postcssCustomProperties({
preserve: false
});
:root {
--color: red;
}
h1 {
color: var(--color);
}
/* becomes */
h1 {
color: red;
}
importFrom
The importFrom
option specifies sources where Custom Properties can be imported
from, which might be CSS, JS, and JSON files, functions, and directly passed
objects.
postcssCustomProperties({
importFrom: 'path/to/file.css'
});
h1 {
color: var(--color);
}
/* becomes */
h1 {
color: red;
}
Multiple sources can be passed into this option, and they will be parsed in the
order they are received. JavaScript files, JSON files, functions, and objects
will need to namespace Custom Properties using the customProperties
or
custom-properties
key.
postcssCustomProperties({
importFrom: [
'path/to/file.css',
'and/then/this.js',
'and/then/that.json',
{
customProperties: { '--color': 'red' }
},
() => {
const customProperties = { '--color': 'red' };
return { customProperties };
}
]
});
See example imports written in CSS,
JS, and JSON.
exportTo
The exportTo
option specifies destinations where Custom Properties can be exported
to, which might be CSS, JS, and JSON files, functions, and directly passed
objects.
postcssCustomProperties({
exportTo: 'path/to/file.css'
});
Multiple destinations can be passed into this option, and they will be parsed
in the order they are received. JavaScript files, JSON files, and objects will
need to namespace Custom Properties using the customProperties
or
custom-properties
key.
const cachedObject = { customProperties: {} };
postcssCustomProperties({
exportTo: [
'path/to/file.css',
'and/then/this.js',
'and/then/this.mjs',
'and/then/that.json',
cachedObject,
customProperties => {
customProperties
}
]
});
See example exports written to CSS,
JS, MJS, and
JSON.