Import SVG as a component in Gatsby

喜欢而已 提交于 2021-01-15 15:46:42

问题


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, and react@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:


  1. Add new package:

npm install gatsby-plugin-react-svg

or

yarn add gatsby-plugin-react-svg

  1. 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/,
        },
      },
    },
  ],
};
  1. Rename your files to something like example.inline.svg

  2. Import:

import Illustration from './illustration.inline.svg'
  1. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!