From 1a50effd861fdf773578f231e3ee668a01fb1744 Mon Sep 17 00:00:00 2001 From: RMidhunSuresh Date: Fri, 25 Mar 2022 18:21:03 +0530 Subject: [PATCH] Only extract into variables if file is svg --- scripts/postcss/css-url-to-variables.js | 11 ++++++++--- .../postcss/tests/css-url-to-variables.test.js | 16 +++++++++++----- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/scripts/postcss/css-url-to-variables.js b/scripts/postcss/css-url-to-variables.js index aff8eef9..2a2937c0 100644 --- a/scripts/postcss/css-url-to-variables.js +++ b/scripts/postcss/css-url-to-variables.js @@ -31,9 +31,12 @@ function findAndReplaceUrl(decl) { if (node.type !== "function" || node.value !== "url") { return; } - const urlStringNode = node.nodes[0]; + const url = node.nodes[0].value; + if (!url.match(/\.svg\?primary=.+/)) { + return; + } const variableName = `${idToPrepend}-${counter++}`; - urlVariables.set(variableName, urlStringNode.value); + urlVariables.set(variableName, url); node.value = "var"; node.nodes = [{ type: "word", value: `--${variableName}` }]; }); @@ -61,7 +64,9 @@ module.exports = (opts = {}) => { Once(root, { Rule, Declaration }) { root.walkDecls(decl => findAndReplaceUrl(decl)); - addResolvedVariablesToRootSelector(root, { Rule, Declaration }); + if (urlVariables.size) { + addResolvedVariablesToRootSelector(root, { Rule, Declaration }); + } }, }; }; diff --git a/scripts/postcss/tests/css-url-to-variables.test.js b/scripts/postcss/tests/css-url-to-variables.test.js index fe4d4865..cc7d9cd2 100644 --- a/scripts/postcss/tests/css-url-to-variables.test.js +++ b/scripts/postcss/tests/css-url-to-variables.test.js @@ -21,10 +21,10 @@ module.exports.tests = function tests() { return { "url is replaced with variable": async (assert) => { const inputCSS = `div { - background: no-repeat center/80% url("../img/image.png"); + background: no-repeat center/80% url("../img/image.svg?primary=main-color--darker-20"); } button { - background: url("/home/foo/bar/cool.jpg"); + background: url("/home/foo/bar/cool.svg?primary=blue&secondary=green"); }`; const outputCSS = `div { @@ -35,12 +35,18 @@ module.exports.tests = function tests() { }`+ ` :root { - --icon-url-0: url("../img/image.png"); - --icon-url-1: url("/home/foo/bar/cool.jpg"); + --icon-url-0: url("../img/image.svg?primary=main-color--darker-20"); + --icon-url-1: url("/home/foo/bar/cool.svg?primary=blue&secondary=green"); } `; - await run( inputCSS, outputCSS, { }, assert); + await run(inputCSS, outputCSS, { }, assert); }, + "non svg urls without query params are not replaced": async (assert) => { + const inputCSS = `div { + background: no-repeat url("./img/foo/bar/image.png"); + }`; + await run(inputCSS, inputCSS, {}, assert); + } }; };