Define custom css unit and convert them to CSS variable.
Input:
:root {
--cusomt-base-unit: 1vw;
}
div {
width: 100rpx;
}Output:
div {
width: calc(var(--cusomt-base-unit) * 100);
}npm install postcss-custom-css-unitsAdd postcss-custom-css-units plugin to postcss.config.js
module.exports = {
plugins: [
require('postcss-custom-css-units')({
baseUnit: `--cusomt-base-unit`,
customUnit: 'rpx'
})
]
}CSS variable which you defined. customUnit will be converted to that CSS variable.
:root {
--cusomt-base-unit: 1vw;
}Custom CSS unit that should be converted.
div {
width: 100rpx;
}CSS variables get even more powerful when we combine them with the calc(). However, performance can become a problem while using calc() and CSS Variables. Here is the solution to reduce CSS calculation and variables if we don't need them in production environment.
Importing postcss-preset-env and postcss-calc, make sure that preserve is false
module.exports = {
plugins: [
require('postcss-custom-css-units')({
baseUnit: `--cusomt-base-unit`,
customUnit: 'rpx'
}),
require('postcss-preset-env')({
// Some other options...
preserve: false
}),
require("postcss-calc", {
preserve: false
})
]
}Our input CSS
:root {
--cusomt-base-unit: 10px;
}
div {
width: 40rpx;
}will becomes to
div {
width: 400px;
}