10

GitHub - joe223/postcss-custom-css-units: Define custom css unit and convert the...

 3 years ago
source link: https://github.com/joe223/postcss-custom-css-units
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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-units

Usage

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;
}

LICENSE

MIT


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK