Reputation: 361
All im looking to do is use an svg from a sprite file in gatsby but the docs arent very clear, Im stuck at just importing it at the moment, when i try importing the svg it gives me an error:
"svg-sprite-loader exception".
Or if I take the ../ path away I get If you're trying to use a package make sure that 'images/sprite.svg' is installed.
Currently importing like this which it doesnt like:
import sprite from "../images/sprites.svg"
Standard html way
<svg>
<use xlink:href="images/sprites.svg#potato"></use>
</svg>
What gatsby tells you to do
<svg viewBox={sprite.viewBox}>
<use xlinkHref={sprite.potato} />
</svg>
Gatsby config for the svg is
},
"gatsby-plugin-svg-sprite",
{
resolve: `gatsby-plugin-svg-sprite-loader`,
options: {
/* SVG sprite loader options */
pluginOptions: {
/* SVG sprite loader plugin options */
},
},
},
Upvotes: 0
Views: 643
Reputation: 31
I'm the developer of gatsby-plugin-svg-sprite-loader
, now gatsby-plugin-svg-sprites
. You're trying to use the extension with a sprite file, but actually, the plugin expects single SVG images — it'll generate the sprites.svg
file from the SVG images you import on your project. Let's suppose that you have two files, images/potato.svg
and images/tomato.svg
. With this plugin — and I believe that gatsby-plugin-svg-sprite
works the same way —, you must use them like in the following example:
import React from 'react'
import potato from 'images/potato.svg'
import tomato from 'images/tomato.svg'
export default () => (
<>
<svg viewBox={potato.viewBox}>
<use xlinkHref={potato.url} />
</svg>
<svg viewBox={tomato.viewBox}>
<use xlinkHref={tomato.url} />
</svg>
</>
)
The plugin will generate the sprites.svg
file under the hood, so you don't have to worry about it. If you want to use a pre-built sprites file, there's no need to use a plugin. I believe you can use something like the following example:
import React from 'react'
import sprites from 'images/sprites.svg'
export default () => (
<>
<svg viewBox='...'>
<use xlinkHref={`${sprites}#potato`} />
</svg>
<svg viewBox='...'>
<use xlinkHref={`${sprites}#tomato`} />
</svg>
</>
)
You should set the viewBox
property to the correct values of each sprite. Also, make sure that SVGO or any other SVG optimization plugin isn't removing symbols, ids or making any other change that could break your sprite file.
Upvotes: 1
Reputation: 80090
Both gatsby-plugin-svg-sprite-loader
and gatsby-plugin-svg-sprite
are trying to take over SVG loading. Drop gatsby-plugin-svg-sprite
if you intend to use gatsby-plugin-svg-sprite-loader
.
For what it's worth, the instructions provided by gatsby-plugin-svg-sprite-loader
are not provided by Gatsby—it is a community plugin. If you have issues with it you might consider filing an issue with the project repo.
Upvotes: 1