From 06f4d7e5e6ef14fbab6f953774cac64314f3f8c4 Mon Sep 17 00:00:00 2001 From: yoyo837 Date: Mon, 3 Oct 2022 23:41:41 +0800 Subject: [PATCH] feat: add units to config --- README.md | 2 ++ index.js | 8 +++++--- spec/pxtorem-spec.js | 13 +++++++++++++ 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 299809e..320d161 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,7 @@ Type: `Object | Null` Default: ```js { + units: 'rem', rootValue: 16, unitPrecision: 5, propList: ['font', 'font-size', 'line-height', 'letter-spacing'], @@ -72,6 +73,7 @@ Default: } ``` +- `rem` (String) Convert target unit. - `rootValue` (Number | Function) Represents the root element font size or returns the root element font size based on the [`input`](https://api.postcss.org/Input.html) parameter - `unitPrecision` (Number) The decimal numbers to allow the REM units to grow to. - `propList` (Array) The properties that can change from px to rem. diff --git a/index.js b/index.js index 9b9f8a0..30f4bc2 100644 --- a/index.js +++ b/index.js @@ -3,6 +3,7 @@ const filterPropList = require("./lib/filter-prop-list"); const type = require("./lib/type"); const defaults = { + units: 'rem', rootValue: 16, unitPrecision: 5, selectorBlackList: [], @@ -43,13 +44,13 @@ function convertLegacyOptions(options) { }); } -function createPxReplace(rootValue, unitPrecision, minPixelValue) { +function createPxReplace(rootValue, unitPrecision, minPixelValue, units) { return (m, $1) => { if (!$1) return m; const pixels = parseFloat($1); if (pixels < minPixelValue) return m; const fixedVal = toFixed(pixels / rootValue, unitPrecision); - return fixedVal === 0 ? "0" : fixedVal + "rem"; + return fixedVal === 0 ? "0" : fixedVal + units; }; } @@ -145,7 +146,8 @@ module.exports = (options = {}) => { pxReplace = createPxReplace( rootValue, opts.unitPrecision, - opts.minPixelValue + opts.minPixelValue, + opts.units ); }, Declaration(decl) { diff --git a/spec/pxtorem-spec.js b/spec/pxtorem-spec.js index 0ec6d40..fda8488 100644 --- a/spec/pxtorem-spec.js +++ b/spec/pxtorem-spec.js @@ -217,6 +217,19 @@ describe("unitPrecision", function() { }); }); +describe("units", function() { + it("should replace with specified unit", function() { + var expected = ".rule { font-size: 0.938em }"; + var options = { + unitPrecision: 3, + units: 'em' + }; + var processed = postcss(pxtorem(options)).process(basicCSS).css; + + expect(processed).toBe(expected); + }); +}); + describe("propWhiteList", function() { // Deprecate it("should only replace properties in the white list - legacy", function() {