gatsby-plugin-svg-sprites

Gatsby plugin to generate SVG sprites from imported files. The sprites are generated using External SVG Sprite.

Install

$ npm install gatsby-plugin-svg-sprites

Enable the plugin in gatsby-config.js:

module.exports = {
  plugins: [
    'gatsby-plugin-svg-sprites'
  ]
}

Usage

JavaScript

import React from 'react'
import icon from 'images/icon.svg'

export default () => (
  <svg viewBox={icon.viewBox}>
    <use xlinkHref={icon.symbol}/>
  </svg>
)

CSS

.icon {
  background-image: url('images/icon.svg') no-repeat 0;
}

Configure

module.exports = {
  plugins: [
    {
      resolve: 'gatsby-plugin-svg-sprites',
      // options: {
      //   optimize: process.env.NODE_ENV === 'production',
      //   pluginOptions: {
      //     // ...External SVG Sprite plugin options
      //   },
      //   symbolPropertyName
      //   // ...External SVG Sprite loader options
      // }
    }
  ]
}

options

Type: Object. Default: { name: 'sprites.[contenthash].svg', iconName: '[name]--[hash:base64:5]' }.

The options object is passed to External SVG Sprite loader — more info about it can be found here. To keep consistency, name and iconName default values use the same formats used by Gatsby.js for CSS files.

optimize

Type: boolean. Default: process.env.NODE_ENV === 'production'.

With optimize enabled, the sprites ids will be minified. By default, it is enabled on production environments.

pluginOptions

Type: Object. Default: {}.

The pluginOptions parameter is passed to External SVG Sprite plugin.

symbolPropertyName

Type: string or false. Default: false.

By default, External SVG Sprite returns the URL in the symbol property. This option sets another property name to access this value.

— With symbolPropertyName set to url:

import React from 'react'
import icon from 'images/icon.svg'

export default () => (
  <svg viewBox={icon.viewBox}>
    <use xlinkHref={icon.url}/> // Access the sprite URL using `url` property
  </svg>
)

License

The MIT License