Search code examples
cssnode.jsgulpminifypostcss

How to automatically update relative CSS paths for minification?


I would like to update all relative paths for minification, because I use separate folders for each JS/CSS component and folder depth can also be different for each component, for example:

css/
    style.min.css // final minified and processed file
    common.scss
    components/
        gallery/
            gallery.scss // url(../../../img/mypic.png)
img/
    mypic.png

After minification, my style in style.min.css will still have ../../../img/mypic.png. However, it must be updated to ../img/mypic.png, otherwise webbrowsers will not find the picture.

How can I automatically do this with PostCSS or another package?

I found postcss-url project and it provides a function for a custom URL transformation, but I didn't find any example how to do this.

Right now I use gulp, nodejs, autoprefixer and postcss for my minification.


Solution

  • There is a parameter called url in postcss-url that can be used to pass a custom function to postcss-url. This function will be able to modify URLs for postcss-url, but the code must be manually written. Here is what I use in my project:

    var outDir = './src/css'; // output folder for CSS
    gulp.task('min:css', function () {
        return gulp
            .src(cssInput)
            .pipe(postcss([
                autoprefixer(),
                postcssurl({
                    // this function will modify URLs
                    url: function (asset) {
                        if (!asset.url || asset.url.indexOf("base64") !== -1) {
                            return asset.url;
                        }
                        return path.relative(outDir, asset.absolutePath).split("\\").join("/");
                    }
                })
            ]))
            ...
    });