stylis-px2rem-plugin
Version:
A Stylis 4.x plugin that translates pixel units to rem units.
22 lines (20 loc) • 1.02 kB
JavaScript
/* eslint-disable prefer-template */
/* eslint-disable no-param-reassign */
import { DECLARATION } from 'stylis';
const pxRegexp = /"[^"]+"|'[^']+'|url\([^)]+\)|(\d*\.?\d+)px/g;
const stylisPx2RemPlugin = ({ remSize = 16, allowList, blockList } = {}) => (element) => {
if (element.type === DECLARATION) {
const declarationHasPx = element.value.match(pxRegexp);
if (declarationHasPx) {
if (allowList && !allowList.includes(element.props)) return;
if (blockList && blockList.includes(element.props)) return;
const expression = element.children.replace(pxRegexp, (match, group) => (group ? Number(group) / remSize + 'rem' : match));
const reconstructedDeclaration = element.props + ':' + expression + ';';
element.return = reconstructedDeclaration;
}
}
};
// stable identifier that will not be dropped by minification unless the whole module
// is unused
Object.defineProperty(stylisPx2RemPlugin, 'name', { value: 'stylisPx2RemPlugin' });
export default stylisPx2RemPlugin;