Search code examples
cssnpmbase64node-modulesminify

Disable background:url(...) encoding as base64 in Minify package


I use minify to minimize my js and css files. But after minimizing the files, the ones which contain background:url(...) become larger, because the url is encoded to base64.

I want to turn off this css-base64-images function. But according to an issue raised in 2016, this is not possible.

package.json:

  "devDependencies": {
    "minify": "^9.1.0",
    "postcss-cli": "^10.0.0"
  }

My code:

import { minify } from 'minify';

const myFunction = () => {
  /* some code... */

  minify(filepath).then((file) => {
                    /* some code... */
  });
}

According to this article, in most cases, it is not neccessary to optimize images with base64. In my case some css files have grown to10,000 KB from 40-50 KB, therefore I want to turn of base64.


Solution

  • I figured out a solution to "turn off" base64.

    The minify function accepts 2 parameters, name and userOptions.

    The userOptions is passed down to node_modules\css-b64-images\lib\css-b64-images.js. There is the function called replaceUrlByB64, which does not encode to base64, if maxSize is smaller then the file size.

    if (stat.size > options.maxSize){
          return cb(new Error('Skip ' + imageUrl + ' Exceed max size'), css);
    }
    

    My code:

    import { minify } from 'minify';
    
    /* Set image maxSize to 0 to skip url replacement by base64 in minify.
       node_modules/css-b64-images/lib/css-b64-images.js function: replaceUrlByB64 */
    const skipReplacingUrlByB64 = {
        img : {
            maxSize: 0,
        },
    }
    
    const myFunction = () => {
      /* some code... */
    
      minify(filepath, skipReplacingUrlByB64).then((file) => {
                        /* some code... */
      });
    }
    

    The structure of skipReplacingUrlByB64 object is based on how userOptions is retrieved in node_modules\minify\lib\img.js

    const options = {
        ...defaultOptions,
        ...userOptions?.img || {},
    };
    

    package.json is the same as in the question

      "devDependencies": {
        "minify": "^9.1.0",
        "postcss-cli": "^10.0.0"
      }