【问题标题】:Import SVG as a component in Gatsby在 Gatsby 中将 SVG 作为组件导入
【发布时间】:2020-07-24 07:15:20
【问题描述】:

我见过以下解决方案:

import { ReactComponent as Img } from 'path/to/file.svg'

但在盖茨比中,这行不通。我知道存在这方面的插件,但也许可以更轻松地完成。

【问题讨论】:

    标签: reactjs svg import gatsby


    【解决方案1】:

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

    import Icon from "./path/assets/icon.svg";
    

    要安装,您只需要使用npmyarn 添加依赖项,并在您的gatsby-config.js 中使用这个sn-p:

    {
      resolve: 'gatsby-plugin-react-svg',
      options: {
        rule: {
          include: /assets/
        }
      }
    }
    

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

    之后,如果 SVG 的内联样式不适用,您将需要对其进行样式设置。


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

    注意:此功能适用于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 /> 
    

    免责声明: 非插件方法的使用与实现严格相关,它可能对所有场景和用例都适用。

    【讨论】:

    • gatsby-node.jsgatsby-config.js?
    • 你知道为什么 svg 可能没有出现吗?它所在的div是空的
    • 这些是我正在使用的文件 github.com/samgermain/somefiles 。我会尝试做一个 MRE 并发布一个新问题
    • SVG 没有加载? SVG 文件夹只能包含 SVG 文件
    • Well I made one,但它得到一个不同的错误
    【解决方案2】:
    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$/,
            },
          },
        },
    

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

    module.exports = {
      siteMetadata: {
        title: `Gatsby`,
      },
      plugins: [
        {
          resolve: 'gatsby-plugin-react-svg',
          options: {
            rule: {
              include: /assets/,
            },
          },
        },
      ],
    };
    
    1. 将文件重命名为 example.inline.svg

    2. 进口:

    import Illustration from './illustration.inline.svg'
    
    1. 用法:
    <Illustration className="example" />
    

    来自official Gatsby guide的所有信息

    【讨论】:

      【解决方案3】:

      就这样吧……

      import YourDesiredName from 'path/to/file.svg'
      

      【讨论】:

      • 不完全是。这可以用作 img 标签的 src。这个方法: import { ReactComponent as Img } from 'path/to/file.svg' 允许你导入内联 svg。
      猜你喜欢
      • 1970-01-01
      • 2020-08-25
      • 2018-07-31
      • 2018-10-13
      • 2021-08-13
      • 1970-01-01
      • 2021-01-05
      • 1970-01-01
      • 2023-03-25
      相关资源
      最近更新 更多