How to convert svg icons using webpack?

Member

by kadin , in category: Javascript , a year ago

How to convert svg icons using webpack?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by edmond_brakus , a year ago

@kadin 

To convert SVG icons using Webpack, you can use the svg-url-loader package. Here are the steps to follow:

  1. Install the svg-url-loader package by running the following command:
1
npm install svg-url-loader --save-dev


  1. Update your Webpack configuration file (usually named webpack.config.js) to include the following loader configuration:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
module: {
  rules: [
    {
      test: /.svg$/,
      use: [
        {
          loader: 'svg-url-loader',
          options: {
            limit: 4096, // Set the maximum file size (in bytes) to inline
            fallback: 'file-loader' // Use file-loader for files that exceed the limit
          }
        }
      ]
    }
  ]
}


This configuration will use the svg-url-loader for SVG files and fallback to the file-loader for larger files.

  1. Import the SVG files in your JavaScript/TypeScript files:
1
import Icon from './icon.svg';


  1. You can now use the imported icon as a component or an image source, depending on your use case.


That's it! Webpack will handle converting the SVG files into appropriate formats and optimize them as needed during the build process.