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

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

问题描述

我看到了以下解决方案:

I've seen the following solution:

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

但是在 Gatsby 中,这不起作用.我知道存在用于此的插件,但也许可以更轻松地完成.

But in Gatsby, this doesn't work. I know exist plugins for this, but maybe it can be done more easily.

推荐答案

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

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";

要安装,您只需要使用 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 文件.换句话说,如果您的路径是 /images/svg/ 您的包含规则只能包含 /svg/ (您也可以添加完整路径,但您需要转义斜杠).

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 can only contain /svg/ (you can also add the full path but you'll need to escape slashes).

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

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

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

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:

注意:此功能可用于 react-scripts@2.0.0 或更高版本,和 react@16.3.0 或更高版本.

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/

像这样使用:

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

...

  <YourIcon/>
  <Email /> 


免责声明:非插件方法的使用与实现严格相关,它可能不适用于所有场景或用例.


Disclaimer: The non-plugin approach use is strictly related to the implementation, it may work for everyone neither in all scenarios nor use-cases.

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

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