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

2k views Asked by At

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'),
    }),
]
3

There are 3 answers

0
tcconstantin On BEST ANSWER

A possible solution would be to use postcss-url:

import postcssurl from 'postcss-url';

postcss({
 ..., // postcss options
 plugins: [
   postcssurl({
     url: 'inline',
   }),
 ],
}),
0
Njuguna Mureithi On

You can use postcss-inline-base64

Here is a working example based on this rollup starter:

import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import { terser } from 'rollup-plugin-terser';
import path from 'path'

import postcss from 'rollup-plugin-postcss'
import base64Inliner from 'postcss-inline-base64'


// `npm run build` -> `production` is true
// `npm run dev` -> `production` is false
const production = !process.env.ROLLUP_WATCH;
const __dirname = path.resolve();
const baseDir = path.join(__dirname, 'public')


export default {
    input: 'src/main.js',
    output: {
        file: 'public/bundle.js',
        format: 'iife', // immediately-invoked function expression — suitable for <script> tags
        sourcemap: true
    },
    plugins: [
        postcss({
            extensions: ['.css'],
            extract: path.resolve('public/styles.css'),
            plugins: [base64Inliner({ baseDir })]
        }),
        ...
    ]
};

I then created a css file in the src folder:

body {
    background: url('b64---./images/test.png---');
}

In index.js:

import "./styles.css";

In index.html

....
<title>rollup-starter-app</title>
<link href="styles.css" rel="stylesheet" />
....

I was able to get:

inlined base64

1
Aqua On

I am not not sure if it is possible with rollup-plugin-postcss, Try using “image-to-base64” npm it’s very simple, Download command :

npm i -S image-to-base64

Example :

const imageToBase64 = require('image-to-base64');
//or
//import imageToBase64 from 'image-to-base64/browser';

imageToBase64("path/to/file.jpg") // Path to the image
    .then(
        (response) => {
            console.log(response); // "cGF0aC90by9maWxlLmpwZw=="
        }
    )
    .catch(
        (error) => {
            console.log(error); // Logs an error if there was one
        }
    )

There is more examples here

https://www.npmjs.com/package/image-to-base64

If you need more help you can reply to this comment.