PostCSS plugin to work around CSS Modules values limitations.
Replaces CSS Modules @values just as postcss-modules-values does, but without help of css-loader, so it could be used before other PostCSS plugins like postcss-calc.
Example:
/* constants.css */
@value unit: 8px;
@value footer-height: calc(unit * 5);
/* my-components.css */
@value unit, footer-height from "./constants.css";
@value component-height: calc(unit * 10);
.my-component {
padding: unit;
margin-top: footer-height;
height: component-height;
}yields my-components.css:
@value unit, footer-height from "./constants.css";
@value component-height: calc(8px * 10);
.my-component {
padding: 8px;
margin-top: calc(8px * 5);
height: calc(8px * 10);
}and leads to export of following values to JS:
{
"unit": "8px",
"footer-height": "calc(8px * 5)",
"component-height": "calc(8px * 10)",
...
}See how to export computed values in usage with calc example below.
Place it before other plugins:
postcss([ require('postcss-modules-values-replace'), require('postcss-calc') ]);To make it faster in webpack pass its file system to plugin:
{
postcss: webpack => [
require('postcss-modules-values-replace')({fs: webpack._compiler.inputFileSystem}),
require('postcss-calc')
]
}Or in postcss.config.js form:
module.exports = (ctx) => ({
plugins: [
require('postcss-modules-values-replace')({fs: ctx.webpack._compiler.inputFileSystem}),
require('postcss-color-function'),
]
});See PostCSS docs for examples for your environment.
To enable calculations inside @value, enable media queries support in postcss-calc:
postcss([
require('postcss-modules-values-replace'),
require('postcss-calc')({mediaQueries: true})
])or via postcss-cssnext:
postcss([
require('postcss-modules-values-replace'),
require('postcss-cssnext')({features: {calc: {mediaQueries: true}}})
])Example with calc enabled:
/* constants.css */
@value unit: 8px;
@value footer-height: calc(unit * 5);
/* my-components.css */
@value unit, footer-height from "./constants.css";
@value component-height: calc(unit * 10);
.my-component {
padding: unit;
margin-top: footer-height;
height: component-height;
}yields my-components.css:
@value unit, footer-height from "./constants.css";
@value component-height: 80px;
.my-component {
padding: 8px;
margin-top: 40px;
height: 80px;
}and leads to export of following values to JS:
{
"unit": "8px",
"footer-height": "40px",
"component-height": "80px",
...
}postcss-color-function and other plugins probably won't work inside @value as they don't traverse media queries.
This plugin provides to postcss a custom messages object with type: 'values'.
The values property of that object will contain all the extracted values with all substitution performed (i.e. for values that reference other values).
See modules-values-extract for an example of how this can be used.
Node.js 6.5 or above is recomended.
ISC
Code is mostly taken from postcss-modules-values by Glen Maddern, Mark Dalgleish and other contributors.