如何将 purgeCss 与其他模块导出一起使用?

How to use purgeCss with other module exports?

我想在我的 NextJS 项目中使用 purgeCss。 在文档中它说我应该改变我的 next.config.js 是这样的:

module.exports = withCss(withPurgeCss())

但是我应该在哪里设置当前配置?

module.exports = {
    distDir: '../.next',
    webpack: config => {
        const env = Object.keys(process.env).reduce((acc, curr) => {
            acc[`process.env.${curr}`] = JSON.stringify(process.env[curr]);
            return acc;
        }, {});

        config.resolve.modules.push(path.resolve('./'));
        config.plugins.push(new webpack.DefinePlugin(env));

        return config;
    },
};

我的postcss.config.js:

module.exports = {
    "plugins": [
        "postcss-flexbugs-fixes",
        [
            "postcss-preset-env",
            {
                "autoprefixer": {
                    "flexbox": "no-2009"
                },
                "stage": 3,
                "features": {
                    "custom-properties": false
                }
            }
        ],
        [
            '@fullhuman/postcss-purgecss',
            {
                content: [
                    './pages/**/*.{js,jsx,ts,tsx}',
                    './components/**/*.{js,jsx,ts,tsx}'
                ],
                defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || [],
                safelist: ["html", "body"]
            }
        ],
    ]
}

您的配置对象进入最里面的插件调用。

// next.config.js

module.exports = withCss(withPurgeCss({
    distDir: '../.next',
    webpack: config => {
        const env = Object.keys(process.env).reduce((acc, curr) => {
            acc[`process.env.${curr}`] = JSON.stringify(process.env[curr]);
            return acc;
        }, {});

        config.resolve.modules.push(path.resolve('./'));
        config.plugins.push(new webpack.DefinePlugin(env));

        return config;
    },
}))

要解决 postcss.config.js 的后续问题,请将其替换为基于对象的格式(如 Next.js documentation 中所示 - 它就在页面底部):

module.exports = {
    'plugins': {
        'postcss-flexbugs-fixes': {},
        'postcss-preset-env': {
            'autoprefixer': {
                'flexbox': "no-2009"
            },
            'stage': 3,
            'features': {
                'custom-properties': false
            }
        },
        '@fullhuman/postcss-purgecss': {
            'content': [
                './pages/**/*.{js,jsx,ts,tsx}',
                './components/**/*.{js,jsx,ts,tsx}'
            ],
            'defaultExtractor': content => content.match(/[\w-/:]+(?<!:)/g) || [],
            'safelist': ['html', 'body']
        },
    }
}