Bayan Abuawad
Bayan Abuawad

Reputation: 134

Angular 8 - Replace image URL with inline base64 on production build

I am trying to change all the images of a certain page from a file path to base64, I read that sens Angular 6 we can no longer add custom code to Webpack configurations, and I am not interested in using a custom builder like @angular-builders/custom-webpack as a solution.

is this possible?

Thanks in advance.

Upvotes: 0

Views: 868

Answers (1)

yazantahhan
yazantahhan

Reputation: 3110

You can create a Node script as the following:

const fs = require('fs');
const base64Img = require('base64-img');

fs.readFile('my/file/path', 'utf8', (err, data) => {
  if (err) {
    return console.error(err);
  }
  const matches = data.match(/assets\/.*?(svg|png)/g);
  matches.forEach(match => {
    try {
      if (fs.existsSync(match)) {
        const convertedImage = base64Img.base64Sync(match);
        data = data.replace(match, `${convertedImage}`);
      }
    } catch (err) {
      console.error('Error: File not found', match);
    }
  });

  fs.writeFile('my/destination/file', data, 'utf8', (err) => {
    if (err) {
      return console.error(err);
    }
  });
});

In this way, it will get the file that you need to replace the files, search for the assets, then convert the images to base64 and replace them. The last step is to write the result to a new file.

To run this, you need to install base64-img library: npm i base64-img --save-dev. Afterwards, you can build the project and then run node include-images.js.

To make it easier, you can also add a script in your package.json, something like:

"replace-images": "ng build && node include-images.js"

This can be run using: npm run replace-images

Please note that I don't prefer converting the images into base64 and include it in the bundle as it will make the bundle / bundles much bigger and will decrease your website performance.

Upvotes: 1

Related Questions