Adding an SVG component to Gatsby (React)
April 6, 2020
Problem
Gatsby importiert SVGs standardmaessig als Datei-URL, nicht als React Component.
Loesungen
1) SVGR Plugin
Mit gatsby-plugin-react-svg kannst du SVGs als Komponenten importieren.
code
npm i gatsby-plugin-react-svg
gatsby-config.js:
code
{
resolve: "gatsby-plugin-react-svg",
options: {
rule: {
include: /assets\/icons/
}
}
}
Nutzung:
code
import { ReactComponent as Logo } from "../assets/icons/logo.svg";
<Logo />;
2) SVG als img (Fallback)
code
import logo from "/images/notes/gatsby/logo.svg";
<img src={logo} alt="logo" />;
Hinweis
Inline SVG ist besser, wenn du Farben/Media Queries steuern willst.