Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 316
Prisacari Dmitrii Avatar asked May 16 '19 12:05

Prisacari Dmitrii


2 Answers

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.

like image 164
Prisacari Dmitrii Avatar answered Oct 22 '22 07:10

Prisacari Dmitrii


The simplest way to reference the svg file without any transformation would be handling it as a static asset. Put the svg file in the static asset directory and copy it as you bundle the source code. You can achieve it by using copy-webpack-plugin. Below is a sample setup in webpack.config.js:

const CopyPlugin = require('copy-webpack-plugin');

// ...

plugins: [
  new CopyPlugin([
    {
      from: './src/static/assets/sprite.svg',
      to: 'static/assets', // relative path in output directory
    }
  ])
]

Once you successfully copy the svg file to the static assets folder, you can reference it like you did in your above code.

like image 32
cypark Avatar answered Oct 22 '22 07:10

cypark