How to create a svg sprite on Laravel MIX?

4k views Asked by At

I need to configure the build SVG sprites on laravel mix.
I tried several libraries under webpack, result = 0.

Can someone advise how to configure?

Where to write the handler code in webpack.mix.js or app.js?

1

There are 1 answers

0
Priit On

One way I was able to get SVG sprites working with Laravele Mix & svg-spritemap-webpack-plugin.

First install the spritemap plugin

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

Then add config webpack.mix.js like that:

const mix = require('laravel-mix');
const SVGSpritemapPlugin = require('svg-spritemap-webpack-plugin');

// Set up the spritemap plugin
mix.webpackConfig({
    plugins: [
        new SVGSpritemapPlugin({
            src:'assets/svg/icons/*.svg',
            filename: '/svg/icons.svg',
            prefix: '',
            svg4everybody: true,
            svgo: {
                removeTitle: true,
                removeStyleElement: true,
                cleanupNumericValue: true,
            },
        })
    ]
});

// Adapt laravel-mix webpack config to better handle svg images.
Mix.listen('configReady', (webpackConfig) => {

    // Add separate svg loader
    webpackConfig.module.rules.push({
        test: /\.(svg)$/,
        include: /assets\/svg/,
        loaders: [
            {
                loader: 'file-loader',
                options: {
                    name: 'svg/[name].[ext]?[hash]',
                    publicPath: Config.resourceRoot
                }
            },

            {
                loader: 'img-loader',
                options: Config.imgLoaderOptions
            }
        ]
    });

    // Exclude local 'svg' folder from font loader
    let fontLoaderConfig = webpackConfig.module.rules.find(rule => String(rule.test) === String(/\.(woff2?|ttf|eot|svg|otf)$/))
    fontLoaderConfig.exclude = /(assets\/svg)/;

});

With this You should be able to add *.svg files into /resources/assets/svg/*.svg that are copied to public and get an svg sprite made from /resources/assets/svg/icons/*.svg