Search code examples
javascriptcssbundling-and-minificationrollupjs

How to replace url(...) in rollup'd CSS with data URI?


Using rollup and the postcss plugin, I am able to inject CSS into my bundle. However, my CSS references some image files e.g. background-image: url(./images/my-image.svg);.

How can I configure postcss/rollup to replace instances of CSS url(...) with data URIs and thereby embed the SVGs inside of the bundle?


Solution

  • You could use postcss-url plugin to achieve this.

    Install the postcss-url plugin to your project and add it to the postcss plugins array in your rollup config.

    
    const url = require('postcss-url');
    const postcss = require("rollup-plugin-postcss");
    
    export default {
      plugins: [
        postcss({
          plugins: [
            url({
              url: "inline", // enable inline assets using base64 encoding
              maxSize: 10, // maximum file size to inline (in kilobytes)
              fallback: "copy", // fallback method to use if max size is exceeded
            }),
          ],
        }),
      ],
    };
    
    
    

    You can customize the fallback mechanism based on your needs.