在Next.js中使用PostCSS全局数据

brtdzjyr  于 2023-06-22  发布在  其他
关注(0)|答案(1)|浏览(197)

我使用PostCSS与postcss-preset-env(现在是postcss-plugins monorepo的一部分)和postcss-custom-media一起使用,以便能够声明一次全局断点,并在整个项目的CSS模块中使用它们。模块化CSS处理在postcss-custom-media的文档中特别提到,其中建议使用postcss-global-data来允许定义一次变量,并在CSS模块处理期间使用它们。
我已经为Next.js项目创建了一个自定义的PostCSS配置,并遵循了在Next.js中使用postcss-global-data的说明,但到目前为止,我还无法让它在CSS模块中工作。
src/styles/tokens.css中,我定义了我的断点(我在:root{}的内部和外部都尝试过):

/* Breakpoints */
@custom-media --screen-sm (width >= 576px);
@custom-media --screen-md (width >= 768px);
@custom-media --screen-lg (width >= 1200px);

:root {
    /* Breakpoints */
    @custom-media --screen-sm (width >= 576px);
    @custom-media --screen-md (width >= 768px);
    @custom-media --screen-lg (width >= 1200px);
}

我创建了一个自定义的PostCSS配置,用于Next.js。postcss.config.js的内容为:

module.exports = {
    plugins: [
        'postcss-flexbugs-fixes',
        [
            'postcss-preset-env',
            {
                autoprefixer: {
                    flexbox: 'no-2009',
                },
                stage: 3,
                features: {
                    'custom-media-queries': true,
                    // CSS variables aren't compiled because it's not safe.
                    'custom-properties': false,
                    'nesting-rules': true,
                },
            },
        ],
        [
            '@csstools/postcss-global-data',
            {
                files: ['src/styles/tokens.css'],
            },
        ],
    ],
};

在我的一个CSS模块中,我尝试了以下操作:

.heroSearchBox {
    width: 100%;

    @media (--screen-md) {
        max-width: 400px;
    }
}

但这没有任何效果。
我可以证实:
1.我的自定义postcss.config.css的其余部分工作正常
1.如果我把我的自定义断点复制到我的CSS模块css文件中,也可以工作。例如

/* Breakpoints */
@custom-media --screen-sm (width >= 576px);
@custom-media --screen-md (width >= 768px);
@custom-media --screen-lg (width >= 1200px);

.heroSearchBox {
    width: 100%;

    @media (--screen-md) {
        max-width: 400px;
    }
}

然而,这显然会导致大量的重复,就像我希望避免的css导入一样,这也是推荐使用postcss-global-data的原因。
有人能建议什么可能是错的或我如何让这个工作?

cnjp1d6j

cnjp1d6j1#

**已解决。**这是由于我的postcss.config.js文件中配置项的顺序。postcss-global-data必须在postcss-preset-env之前:

module.exports = {
    plugins: [
        'postcss-flexbugs-fixes',
        [
            '@csstools/postcss-global-data',
            {
                files: ['src/styles/media-queries.css'],
            },
        ],
        [
            'postcss-preset-env',
            {
                autoprefixer: {
                    flexbox: 'no-2009',
                },
                stage: 3,
                features: {
                    'custom-media-queries': true,
                    // CSS variables aren't compiled because it's not safe.
                    'custom-properties': false,
                    'nesting-rules': true,
                },
            },
        ],
    ],
};

相关问题