postcss-custom-css-units
v0.1.0
Published
PostCSS plugin to define custom units
Readme
PostCSS Custom CSS Units
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);
}Installation
npm install postcss-custom-css-unitsUsage
Add postcss-custom-css-units plugin to postcss.config.js
module.exports = {
plugins: [
require('postcss-custom-css-units')({
baseUnit: `--cusomt-base-unit`,
customUnit: 'rpx'
})
]
}Options
baseUnit (default: --base-unit)
CSS variable which you defined. customUnit will be converted to that CSS variable.
:root {
--cusomt-base-unit: 1vw;
}customUnit (default: rpx)
Custom CSS unit that should be converted.
div {
width: 100rpx;
}Optimize CSS performance
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;
}