Search code examples
javascriptrollupjsrollup-plugin-postcss

Replace all image paths in a css file with base64 encoded strings - rollup


I am trying to replace all the image paths in a css background url to a base64 encoded string while doing a rollup build.

I am using rollup-plugin-postcss for this, I am able to generate a separate .css file in the build, but I want the image paths to be replaced with base64 encoded data URL.

Something like this:

background: url('images/sample.png');

to

background: url('data:image/png;base64,R0lGODlhyAAiALM...DfD0QAADs=');

Here is what I have been doing:

import postcss from 'rollup-plugin-postcss'

...

plugins: [
    postcss({
        extensions: ['.css'],
        extract: path.resolve('dist/index.css'),
    }),
]

Solution

  • A possible solution would be to use postcss-url:

    import postcssurl from 'postcss-url';
    
    postcss({
     ..., // postcss options
     plugins: [
       postcssurl({
         url: 'inline',
       }),
     ],
    }),