首页 > 解决方案 > PostCSS 插件:如何获取 CSS4 变量的值

问题描述

我将svg-transform-loaderpostcss-move-props-to-bg-image-query一起使用,以便通过 postCSS 修改 SVG 属性。

我不使用postcss-css-variables插件,因此我的 CSS 变量不会转换为纯字符串 - 它们保持原样保留在代码中。

它需要是这样的,因为我不想通过整个 CSS 代码postcss-css-variables,但我想用作一个独立的工具来解析PostCSS 插件回调中的postcss-css-variables一些特定变量。transformpostcss-move-props-to-bg-image-query

我希望能够做到:

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

.img {
  background-image: url('./img.svg');
  -svg-mixer-fill: var(--my-css-variable); // I need `var(--my-css-variable)` to be converted to `blue`
}

当我通过postcss-move-props-to-bg-image-query 插件传递该代码时,var(--my-css-variable)不会对其进行评估-我想使用postcss-css-variables/lib/resolve-value模块来获取此变量的值。

我已经postcss-move-props-to-bg-image-query以一种在transform回调中可以访问rootPostCSSdeclaration对象的方式分叉了。

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,
        };
      },
    }),
  ],
};

现在我被困住了。我不知道如何使用该resolveValue()模块。我知道它declaration作为第一个参数和map对象作为第二个参数,但我不知道如何构建一个合适的map对象。

我不一定需要使用postcss-css-variables/lib/resolve-value- 我只是认为我可以使用它来提取 CSS4 变量的值,因为这就是这个插件在内部所做的。我对任何替代方案持开放态度。

标签: javascriptbuildpostcsscss-variables

解决方案


推荐阅读