Home

Awesome

External SVG Sprite

npm version Build Status

A loader and plugin for webpack that converts all your SVGs into symbols and merges them into a SVG sprite.

Important: There is a breaking change when moving from v3 to v4. Check the release notes.

Requirements

You will need NodeJS v6+, npm v3+ and webpack 4.

To make it work in older browsers, like Internet Explorer, you will also need SVG for Everybody or svgxuse.

Installation

npm i external-svg-sprite-loader

or

yarn add external-svg-sprite-loader

Options

Loader options

Plugin options

Usage

If you have the following webpack configuration:

// webpack.config.js

import path from 'path';

import SvgStorePlugin from 'external-svg-sprite-loader';

module.exports = {
    mode: 'development',
    module: {
        rules: [
            {
                loader: SvgStorePlugin.loader,
                test: /\.svg$/,
            },
        ],
    },
    output: {
        path: path.join(__dirname, 'public'),
        publicPath: '/',
    },
    plugins: [
        new SvgStorePlugin({
            sprite: {
                startX: 10,
                startY: 10,
                deltaX: 20,
                deltaY: 20,
                iconHeight: 20,
            },
        }),
    ],
};

You will be able to import your SVG files in your JavaScript files as shown below. The imported SVG will always correspond to a JavaScript object with keys symbol, view and viewBox:

The URLs will have the following format:

/*
 * {
 *  symbol: '/public/img/sprite.svg#icon-logo',
 *  view: '/public/img/sprite.svg#view-icon-logo',
 *  viewBox: '0 0 150 100',
 *  title: 'Logo'
 * }
 */
import logo from './images/logo.svg';

const Logo = () => (
   <svg viewBox={logo.viewBox} title={logo.title} role="img">
       <use xlinkHref={logo.symbol} />
   </svg>
);

In CSS files, you can import your SVG files as shown bellow (assuming you are using the MiniCssExtractPlugin). The imported value will be converted into the view url shown above.

.special-icon {
    /* the url will be replaced with the url to the sprite */
    background-image: url('./icons/special.svg') no-repeat 0;
}

When a SVG is added, removed or changed, the sprite will be re-generated and all files referencing it will be updated. When no [contenthash] is used in the name option, a cache-busting will be added to the URL so that the browser is forced to re-download the sprite.

Examples

You can find working examples in the examples folder. To test the React example under the examples/react folder run:

npm install
npm run start:dev

And then you can see the result in http://localhost:3000.

There's some additional commands that you may try:

Contributing

First of all, thank you for contributing, you are awesome.

Here are a few rules to follow in order to ease code reviews, and discussions before maintainers accept and merge your work:

Thank you!

License

MIT (http://www.opensource.org/licenses/mit-license.php)