MadLittleMods / postcss-css-variables

PostCSS plugin to transform CSS Custom Properties(CSS variables) syntax into a static representation
https://madlittlemods.github.io/postcss-css-variables/playground/
Other
536 stars 62 forks source link

How to use the resolveValue() as standalone function? #106

Closed wujekbogdan closed 4 years ago

wujekbogdan commented 4 years ago

Hi,

I don't use postcss-css-variables plugin in a standard way. I don't want to pass the whole CSS code through postcss-css-variables. I'd like to use it as a standalone tool to parse only some specific variables within the callback of another postCSS plugin.

I use svg-transform-loader together with postcss-move-props-to-bg-image-query

I'd like to be able to do:

:root {
  --my-css-variable: blue;
}

.img {
  background-image: url('./img.svg');
  -svg-mixer-fill: var(--my-css-variable);
}

When I pass that code through the postcss-move-props-to-bg-image-query plugin then var(--my-css-variable) is not evaluated - I'd like to use postcss-css-variables/lib/resolve-value module to get the value of this variable.

I already forked the postcss-move-props-to-bg-image-query in a way that in the transform callback I have access to root and declaration objects.

const resolveValue = require('postcss-css-variables/lib/resolve-value');
const moveProps = require('postcss-move-props-to-bg-image-query');

module.exports = {
  plugins: [
    moveProps({
      transform: ({ name, value }, root, declaration) => {
        // `name` is '-svg-mixer-fill'
        // `value` is `var(--my-css-variable)`. I'd like to convert it to `blue`

        const map = {
          // I don't know how to use `name` and `value` to create the properly structured object.
        };
        const evaluatedCssVariable = resolveValue(declaration, map); // I'd like it to return `blue`

        return {
          name: name.replace(/^-svg-mixer-/, ''),
          value: evaluatedCssVariable,
        };
      },
    }),
  ],
};

And now I'm stuck. I don't know how to use the resolveValue() module. I know that it takse declaration as a first argument and map object as second argument, but I have no idea how to build a proper map object.

MadLittleMods commented 4 years ago

@wujekbogdan I don't recommend trying to re-use resolve-value.js. It doesn't work very well and it's confusing.

I started on a better generic utility type thing that is probably more what you are after but it's not in any finished sorta state (I just made the project public if you want to look at it though), https://github.com/MadLittleMods/postcss-selector-scope-utility

wujekbogdan commented 4 years ago

@MadLittleMods Thanks for the update. I'll be watching the progress.