【问题标题】:how can I add an subfolder in the url background in the Sass files in production?如何在生产中的 Sass 文件的 url 背景中添加子文件夹?
【发布时间】:2020-03-04 07:29:44
【问题描述】:

NextJS 的开发模式下,我的 SASS 文件中的路径如下例所示:

background-image: url(/images/bg-header.png) !important;

但在生产模式下,我会将网站上传到域的子文件夹中,例如:

www.domain.com/subfolder/

我需要它像这样构建:

background-image: url(/subfolder/images/bg-header.png) !important;

我怎样才能得到它?

另外我在我的配置文件中使用了withCSSwithSass,我尝试了几个next.config.js,但没有任何效果。

const config = {
....
webpack: (config, options) => {
        // config.resolve.alias["@assets"] = '/subfolder/';
        config.plugins.push(
            new MiniCssExtractPlugin({
                    filename: 'static/css/[name].css',
                    chunkFilename: 'static/css/[name].chunk.css',
                    publicPath: '/subfolder/'
            })
        );
        return config
    },
};
module.exports = withSass(withCss(config));

我也试过了,还是不行。

 config.module.rules.push({
            test: /\.(png|jpg|gif|svg|ico)$/,
                use: [
                    {
                        loader: "url-loader",
                        options: {
                            limit: 8192,
                            fallback: "file-loader",
                            publicPath: "/subfolder/",
                            outputPath: "/subfolder/",
                            name: "/subfolder/[name].[ext]"
                        }
                    }
                ]
            });

【问题讨论】:

  • 你也可以使用 postcss-cli 和 postcss-url 插件
  • 非常感谢,由于您的回答,我已经搜索了资料,我已经能够解决了,我会发布答案。

标签: webpack next.js


【解决方案1】:

感谢@grzegorz-t 评论我已经能够解决它,我把解决方案放在这里。

npm install postcss-url --save-dev

postcss.config.js

const isProd = process.env.NODE_ENV === 'production';
const subFolder = isProd ? '/subfolder' : '';

module.exports = {
    plugins: {
        'postcss-url': {
            url: (asset) => {
               if (asset.url[0] === '/'){
                   return subFolder+asset.url
               }
                return asset.url;
            }
        },
        autoprefixer: {}
    }
};

【讨论】:

  • 我几乎只使用 postcss 对 css 进行了所有更改。 Postcss 就是这样一个通天塔,但对于 css;)
猜你喜欢
  • 1970-01-01
  • 2021-01-16
  • 1970-01-01
  • 2022-11-10
  • 2019-12-20
  • 2015-01-21
  • 2021-11-24
  • 2021-10-10
  • 1970-01-01
相关资源
最近更新 更多