将SVG导入为Gatsby中的组件 [英] Import SVG as a component in Gatsby

查看:149
本文介绍了将SVG导入为Gatsby中的组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到以下解决方案:

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.

推荐答案

正如您所说,有一些插件可以实现此目的,这意味着代码更简洁(而不是组件中内联的完整SVG),并具有相同的最终结果.使用此插件,您只需要这样导入SVG:

As you said, there are plugins to achieve this, which means a cleaner code (not the full SVG inlined in the component) with the same final result. Using this plugin you just need to import your SVG like this:

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

要安装,只需使用npmyarn添加依赖项,并在您的gatsby-config.js中使用以下代码段:

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/
    }
  }
}

请注意,/assets/必须是您的SVG文件夹(即/svg/),并且只能包含.svg文件.

Note that /assets/ must be your SVG folder (i.e: /svg/) and must only contain .svg files.

然后,如果它们的内联样式不适用,则需要对SVG进行样式设置.

Afterwards, you will need to style the SVG if their inline styles don't apply.

这篇关于将SVG导入为Gatsby中的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆