Search code examples
angularangular-cliangular-cli-v7

How to use 'url-loader' with angular-cli compiler


Usually I run my projects and build my SASS files with WebPack, which I have the rules in way that generates a CSS file with url-loader converting all url(...) inside that sass file to a dataURI.

Then background: url('my-file.svg') would be converted to background url('data:image/svg+xml;base64,SoMeGiBbeRiShHeRe')

I'd like to know if there is a way to achieve this with the ng compiler? I researched a bit on this, and the way to do it was to use ng eject but that option is no longer available.


Solution

  • I had to do this recently when I was building the virtual background features for the Zoom Video SDK UI Toolkit. Try this:

    Create a file called extra-webpack.config.js in the root of your Angular project with the following:

    module.exports = {
      module: {
        rules: [
          {
            test: /\.(png|jpg|gif|svg)$/i,
            use: [
              {
                loader: 'url-loader'
              },
            ],
          },
        ],
      },
    }
    

    In your angular.json file, add a customWebpackConfig object inside the build object which will tell Angular to use url-loader to convert your images to base64 data:image:

    ...
            "build": {
              "builder": "@angular-builders/custom-webpack:browser",
              "options": {
                "customWebpackConfig": {
                  "path": "./extra-webpack.config.js",
                  "replaceDuplicatePlugins": true
                },
    ...
    

    Once you build your project $ ng build, the image paths will be converted to base64 data:images and your image references will be using the base64 URIs instead of the path to the image.

    Here is an example of my deployed build:

    How to use url-loader with angular-cli compiler