在 Gatsby 中将 SVG 作为组件导入

Bak*_*akr 13 import svg reactjs gatsby

我看到了以下解决方案:

import { ReactComponent as Img } from 'path/to/file.svg'
Run Code Online (Sandbox Code Playgroud)

但在 Gatsby 中,这行不通。我知道存在用于此的插件,但也许可以更轻松地完成。

Fer*_*reu 14

正如您所说,有一些插件可以实现这一点,这意味着更清晰的代码(不是组件中内联的完整 SVG 标记)具有相同的最终结果。使用gatsby-plugin-react-svg插件你只需要像这样导入你的 SVG:

import Icon from "./path/assets/icon.svg";
Run Code Online (Sandbox Code Playgroud)

要安装,您只需要使用npm或添加依赖项,yarn并在gatsby-config.js使用此代码段中:

{
  resolve: 'gatsby-plugin-react-svg',
  options: {
    rule: {
      include: /assets/
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

请注意,这/assets/是基于正则表达式的包含规则,因此该值必须是您的 SVG 文件夹(即:)/svg/并且必须仅包含.svgfiles。换句话说,如果您的路径是/images/svg/您的包含规则只能包含/svg/(您也可以添加完整路径,但您需要转义斜杠)。

之后,如果它们的内联样式不适用,您将需要设置 SVG 的样式。


如果您想遵循create-react-app文档中的非插件方法(也不内联 SVG 标签)来添加 SVG 图像asReact 组件:

注意:此功能可用react-scripts@2.0.0或更高,和react@16.3.0或更高。

来源:https : //create-react-app.dev/docs/adding-images-fonts-and-files/

像这样使用它:

import { ReactComponent as YourIcon} from '../images/svg/yourIcon.svg';
import { ReactComponent as Email } from '../images/svg/email.svg';

...

  <YourIcon/>
  <Email /> 
Run Code Online (Sandbox Code Playgroud)

免责声明:非插件方法的使用严格依赖于实现,它可能适用于所有场景或用例的所有人。


Ily*_*ent 7

  1. 添加新包:

npm install gatsby-plugin-react-svg

或者

yarn add gatsby-plugin-react-svg

  1. 配置在gatsby-config.js
    {
      resolve: 'gatsby-plugin-react-svg',
      options: {
        rule: {
          include: /\.inline\.svg$/,
        },
      },
    },
Run Code Online (Sandbox Code Playgroud)

这是此文件完成后的外观示例

module.exports = {
  siteMetadata: {
    title: `Gatsby`,
  },
  plugins: [
    {
      resolve: 'gatsby-plugin-react-svg',
      options: {
        rule: {
          include: /assets/,
        },
      },
    },
  ],
};
Run Code Online (Sandbox Code Playgroud)
  1. 将您的文件重命名为类似 example.inline.svg

  2. 进口:

import Illustration from './illustration.inline.svg'
Run Code Online (Sandbox Code Playgroud)
  1. 用法:
<Illustration className="example" />
Run Code Online (Sandbox Code Playgroud)

盖茨比官方指南中的所有信息


小智 0

只要这样做...

import YourDesiredName from 'path/to/file.svg'
Run Code Online (Sandbox Code Playgroud)