问题
I've seen the following solution:
import { ReactComponent as Img } from 'path/to/file.svg'
But in Gatsby, this doesn't work. I know exist plugins for this, but maybe it can be done more easily.
回答1:
As you said, there are plugins to achieve this, which means a cleaner code (not the full SVG tag inlined in the component) with the same final result. Using gatsby-plugin-react-svg plugin you just need to import your SVG like this:
import Icon from "./path/assets/icon.svg";
To install, you only need to add the dependency using npm
or yarn
and in your gatsby-config.js
use this snippet:
{
resolve: 'gatsby-plugin-react-svg',
options: {
rule: {
include: /assets/
}
}
}
Note that /assets/
is an including rule based on a regular expression so the value must be your SVG folder (i.e: /svg/
) and must only contain .svg
files. In other words, if your path is /images/svg/
your including rule must only contain /svg/
.
Afterward, you will need to style the SVG if their inline styles don't apply.
If you want to follow the non-plugin approach (also without inlining the SVG tag) from the create-react-app
docs for adding SVG images as react components
Note: this feature is available with
react-scripts@2.0.0
or higher, andreact@16.3.0
or higher.
https://create-react-app.dev/docs/adding-images-fonts-and-files/
Try:
import { ReactComponent as yourIcon} from '../images/svg/yourIcon.svg';
import { ReactComponent as Email } from '../images/svg/email.svg';
...
<YourIcon/>
<Email />
回答2:
- Add new package:
npm install gatsby-plugin-react-svg
or
yarn add gatsby-plugin-react-svg
- Configure at
gatsby-config.js
:
{
resolve: 'gatsby-plugin-react-svg',
options: {
rule: {
include: /\.inline\.svg$/,
},
},
},
Here's an example of what this file might look like when completed
module.exports = {
siteMetadata: {
title: `Gatsby`,
},
plugins: [
{
resolve: 'gatsby-plugin-react-svg',
options: {
rule: {
include: /assets/,
},
},
},
],
};
Rename your files to something like
example.inline.svg
Import:
import Illustration from './illustration.inline.svg'
- Usage:
<Illustration className="example" />
All the information from official Gatsby guide
回答3:
Just do like this...
import YourDesiredName from 'path/to/file.svg'
回答4:
For importing svg image as React component, use https://react-svgr.com/docs/webpack They have webpack module, very simple configuration and worked for me on first try. Great benefit is you can change svg image props e.g. fill color. Let me know if I can help you with it.
来源:https://stackoverflow.com/questions/61158924/import-svg-as-a-component-in-gatsby