htmlcsssvgwebpacksvg-sprite

How to configure webpack to use a prebuilt svg sprite?


I have a prebuilt svg sprite with more than 100 icons:

<svg xmlns="http://www.w3.org/2000/svg" style="visibility:hidden; width:0; height:0;">
    <symbol id="icon--web" viewBox="0 0 70 100">...</symbol>
    ...
</svg>

How to configure webpack to use such a sprite in this simple way? :

<svg class="icon icon--web">
    <use xlink:href="../../images/sprite.svg#icon--web"></use>
</svg>

Most of plugins (svg-spritemap-webpack-plugin, svg-sprite-loader) are aimed to build sprites from many svg images, however I've not found how to configure them to use an earlier built sprite.


Solution

  • So here's my solution for webpack4. This results to that svg sprite is included in javascript application code and is inserted into the page markup after opening body tag and all icons from the sprite are successfully loaded:

    1. Include sprite path to your index.js file:

      // index.js
      import '../images/_sprite.svg';
      
    2. Add rule to webpack config (use svg-sprite-loader):

      {
          test: /\.svg$/i,
      
          // from all svg images
          // include only sprite image
          include: /.*_sprite\.svg/,
      
          use: [
              {
                  loader: 'svg-sprite-loader',
                  options: {
                      publicPath: '',
                  }
              },
          ],
      },
      
      
    3. Enable svg-sprite-loader plugin in your webpack config:

      const SpriteLoaderPlugin = require('svg-sprite-loader/plugin');
      
      // ...
      plugins: [
          // ...
          new SpriteLoaderPlugin()
      ]
      
    4. Use the following html markup in your html:

      <svg class="icon icon--web">
          <use xlink:href="#_sprite_icon--web"></use>
      </svg>
      

      Pay attention that the sprite path is removed and the _sprite_ string is added.