gpt4 book ai didi

reactjs - 在 Gatsby 中将 SVG 作为组件导入

转载 作者:行者123 更新时间:2023-12-04 04:24:33 24 4
gpt4 key购买 nike

我看到了以下解决方案:

import { ReactComponent as Img } from 'path/to/file.svg'
但在 Gatsby 中,这行不通。我知道存在用于此的插件,但也许可以更轻松地完成。

最佳答案

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

import Icon from "./path/assets/icon.svg";
要安装,您只需要使用 npm 添加依赖项即可。或 yarn并在您的 gatsby-config.js使用这个片段:
{
resolve: 'gatsby-plugin-react-svg',
options: {
rule: {
include: /assets/
}
}
}
请注意 /assets/是基于正则表达式的包含规则,因此值必须是您的 SVG 文件夹(即: /svg/ )和 必须只包含 .svg文件 .换句话说,如果你的路径是 /images/svg/您的包含规则只能包含 /svg/ (您也可以添加完整路径,但您需要转义斜杠)。
之后,如果它们的内联样式不适用,您将需要设置 SVG 的样式。

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

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

关于reactjs - 在 Gatsby 中将 SVG 作为组件导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61158924/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com