Inline images as base64 in Angular build with custom webpack config

521 views Asked by At

I have an Angular project, which only contains web-components. In order to include the assets (only images) for the components, I wanted to use a custom webpack-config in order to use the url-loader or something similar to convert the images used in the component into inline base64 images.

I successfully setup the @angular-builders/custom-webpack and verified that it loads my webpack.config.js. After a lot of trial and error this currently looks like this (but is still not working):

// your custom webpack config
module.exports = config => {
  // I verified that the rule for loading images is the first element of the array
  config.module.rules.shift(); 
  config.module.rules = [
    ...config.module.rules,
    {
      test: /\.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)$/,
      loader: 'base64-inline-loader',
      options: {
        name: '[name].[ext]'
      }
    }
  ];

  return config;
};

I tried just putting a config option, because it should be automatically merged, but that didn't work, so I wrote the function to really overwrite the default Angular image loader.

edit: I found out that I can specifically use the webpack url-loader from the code like this:

declare const require;

@Component({...})
export class AComponent {
  logoUrl = require('!!url-loader!logo.svg');
}

This kind of works and could be a way to tackle this, since it's only used in a web-component only project. This will however not work in my .scss files, I assume and I would prefer to find a solution without having to remember special knowledge for the library.

0

There are 0 answers