postcss-plugin-px2var
v0.1.2
Published
A plugin for PostCSS that generates var units from multi units.
Downloads
18
Readme
postcss-plugin-px2var
A PostCSS plugin that replaces px values with a CSS Variable-powered scale using calc. It turns 10px into calc(10*var(--your-unit)) so you can control a global sizing scale via a single CSS variable.
Features
- Converts
pxvalues tocalc(<px>*var(--your-unit)) - Skips values already using the configured CSS variable
- Supports selector and property blacklists
- Optional inline or comment-based ignore tokens per declaration
- Ignores
pxinside quoted strings andurl(...)
Installation
npm i postcss-plugin-px2varUsage (PostCSS API)
const fs = require('fs');
const postcss = require('postcss');
const px2var = require('postcss-plugin-px2var');
const css = fs.readFileSync('src/styles/app.css', 'utf8');
const options = {
include: /my-project\/(src|styles)/i, // required: only files matching this regex are processed
cssVariable: '--ke-unit', // required: the CSS variable to multiply by
cssVariableFallback: (origin, num, unit) => origin, // optional: css var fallback function: (origin, num, unit) => { return origin }
cssVariableFallbackOrigin: false, // optional: fallback to origin if cssVariableFallback is not set
replace: true, // replace in-place; if false, add a cloned declaration after
selectorBlackList: [/^\.no-scale/], // optional: selectors to skip
propBlackList: ['border-width'], // optional: properties to skip
ignoreIdentifier: 'no-px', // optional: token to skip individual declarations
};
postcss([px2var(options)])
.process(css, { from: 'src/styles/app.css', to: 'dist/app.css' })
.then((result) => {
fs.writeFileSync('dist/app.css', result.css);
});Input / Output
/* input */
h1 {
margin: 0 0 20px;
font-size: 32px; /* no-px */
line-height: 1.2;
border-width: 1px;
}
/* output (with cssVariable: --ke-unit, propBlackList: ['border-width']) */
h1 {
margin: 0 0 calc(20 * var(--ke-unit, 32px));
font-size: 32px; /* no-px */
line-height: 1.2;
border-width: 1px;
}Notes:
- Declarations with
ignoreIdentifiertoken are skipped. You can also place it as a trailing comment:font-size: 16px; /* no-px */. - Declarations or property names that already include
cssVariableare skipped. pxinside quotes orurl(...)is ignored.
Options
{
include: undefined, // RegExp (required): processed only if file path matches
cssVariable: '', // String (required): e.g. '--ke-unit'
cssVariableFallback: undefined, // Function (optional): css var fallback function: (origin, num, unit) => { return origin }
cssVariableFallbackOrigin: false, // Boolean: fallback to origin if cssVariableFallback is not set
selectorBlackList: [], // Array<String|RegExp>: selectors to skip
propBlackList: [], // Array<String|RegExp>: properties to skip
ignoreIdentifier: false, // String|false: token to mark declaration to skip
replace: true // Boolean: true to replace, false to insert cloned declaration after
}includeRegExp matched against the absolute file path. If not set or doesn't match, no changes are made.cssVariableThe CSS variable name used incalc, e.g.--ke-unit.cssVariableFallbackOptional fallback function for CSS variable. If not set,originis returned.cssVariableFallbackOriginOptional fallback to origin ifcssVariableFallbackis not set. Defaults tofalse.selectorBlackListSkip rules whose selector matches any string (substring) or RegExp.propBlackListSkip declarations whose property matches any string (substring) or RegExp.ignoreIdentifierWhen set to a string token (e.g.'no-px'), skip declarations that contain this token in the value or have it as the next sibling comment.replaceIftrue, declaration value is replaced. Iffalse, a cloned declaration with the converted value is inserted right after the original (you keeppxas fallback).
PostCSS Config / Bundlers
Create postcss.config.js:
module.exports = {
plugins: [
require('postcss-plugin-px2var')({
include: /my-project\/(src|styles)/i,
cssVariable: '--ke-unit',
cssVariableFallback: (origin, num, unit) => origin,
cssVariableFallbackOrigin: false,
selectorBlackList: [/^\.no-scale/],
propBlackList: ['border-width'],
ignoreIdentifier: 'no-px',
replace: true,
}),
],
};Example CSS variable definition (global scale):
:root {
--ke-unit: 0.01rem;
} /* every px becomes px * 0.01rem */How It Works
- The plugin scans declaration values for
pxand replaces them withcalc(<number>*var(--your-unit)). - It performs several guards: file path must match
include,cssVariablemust be provided, selector/property blacklists, and ignore token. - Text inside quotes and
url(...)is intentionally preserved.
License
MIT
