Create a SVG Sprite - configuration of webpack.mix.js

I am assuming, that you are using Pyro (cms) version 3.4, and have your own custom theme.

Install svg-spritemap-webpack-plugin

First, we have to install this package:

npm install --save-dev svg-spritemap-webpack-plugin

We need SVGS!

My favourite place to find great svg icons is over at Flaticon. So in this example i am heading over there, and grabbing a linkedin icon. I save this icon to : myproject.dev/resources/assets/svgs/linkedin.svg

webpack.mix.js

We have to add some more configuration to our webpack.mix.js file. Below, is the version i use for this homepage:

let mix = require('laravel-mix');
var SVGSpritemapPlugin = require('svg-spritemap-webpack-plugin');
var svgSpriteDestination = "../addons/williamastrom/pixney/williamastrom-theme/resources/views/partials/svgs/svgs.twig"

mix.sass('resources/assets/sass/app.scss', 'public/css')
.webpackConfig({
    plugins: [
        new SVGSpritemapPlugin({
           src: 'resources/assets/svgs/*.svg',
           filename : svgSpriteDestination,
           svgo : {removeTitle : true}
        })
    ] 
});

Important! As you know from my previous blogpost about setting up Pyro version 3.4 and using mix, the directory resources is referring to the regular Laravel resources directory and not your Pyro theme resources directory.

However, when saving the svg sprite, i do so in my theme under partials/svgs/ to make sure it's easier for me to use within Pyro.

Include the sprite in your theme

You would want to include the generated sprite at the very end of your HTML body. I wrap it in a div set to display:none to make sure the sprite content is not shown on your website.

<div style="display:none">
    {% include 'theme::partials/svgs/svgs' %}
</div>

How to add the svg icon to your design

Whenever you would like your icon to be displayed on your homepage, you simply reference the svg you want to use by its ID :

<svg>
    <use xlink:href="#sprite-linkedin"/>
</svg>

As usual, you are able to set a class to the svg element to be able to add custom styling to it from your stylesheet:

<svg class="icon icon--linkedin">
    <use xlink:href="#sprite-linkedin"/>
</svg>
linkedinfacebook