Migrate to Netlify Today

Netlify announces the next evolution of Gatsby Cloud. Learn more

ContactSign Up
Community Plugin
View plugin on GitHub

gatsby-transformer-inline-svg

npm npm

Maintainability Contributor Covenant

Read and optimize (Contentful) SVG file nodes to render them inline in your website.

If you want to render static SVG files, use https://www.gatsbyjs.org/packages/gatsby-plugin-react-svg/.

Features

  • Read content of your SVG files from gatsby-source-contentful and gatsby-source-filesystem.
  • Provides original SVG content for further processing
  • Optimizes output via SVGO
  • Provides a compact data URI via mini-svg-data-uri
  • Downloads svg and caches it via createRemoteFileNode

Installation

npm i gatsby-transformer-inline-svg

Usage

Pass your server connection credentials, the remote cache directory and the directories you want to cache to the plugin options in your gatsby-config.js:

gatsby-config.js:

module.exports = {
  plugins: [
    `gatsby-transformer-inline-svg`
  ]
}

GraphQL Query:

... on ContentfulAsset {
  svg {
    content # SVG content optimized with SVGO
    originalContent # Original SVG content
    dataURI # Optimized SVG as compact dataURI
    absolutePath #
    relativePath #
  }
  file {
    contentType
    url
    fileName
  }
}
... on File {
  svg {
    content # SVG content optimized with SVGO
    originalContent # Original SVG content
    dataURI # Optimized SVG as compact dataURI
    absolutePath #
    relativePath #
  }
  absolutePath
  name
  internal {
    mediaType
  }
}

Rendering:

import React from 'react'
import propTypes from 'prop-types'
import GatsbyImage from 'gatsby-plugin-image'

// Render inline SVG with fallback non-svg images
export default function Image({ svg, gatsbyImageData, file, alt }) {
  if (file.contentType === 'image/svg+xml') {
    if (svg && svg.content) {
      // Inlined SVGs
      return <div dangerouslySetInnerHTML={{ __html: svg.content }} />
    }

    // SVGs that can/should not be inlined
    return <img src={file.url} alt={alt} />
  }

  // Non SVG images
  return <GatsbyImage image={gatsbyImageData} alt={alt} />
}
© 2023 Gatsby, Inc.