我已经看到以下解决方案:
import { ReactComponent as Img } from 'path/to/file.svg'
但在盖茨比中,这行不通。我知道存在用于此的插件,但也许可以更轻松地完成。
我已经看到以下解决方案:
import { ReactComponent as Img } from 'path/to/file.svg'
但在盖茨比中,这行不通。我知道存在用于此的插件,但也许可以更轻松地完成。
正如您所说,有一些插件可以实现这一点,这意味着更清晰的代码(不是组件中内联的完整 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
files。换句话说,如果您的路径是/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 />
免责声明:非插件方法的使用与实现密切相关,它可能适用于所有人,既不适用于所有场景,也不适用于用例。
npm install gatsby-plugin-react-svg
或者
yarn add gatsby-plugin-react-svg
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/,
},
},
},
],
};
将您的文件重命名为类似 example.inline.svg
进口:
import Illustration from './illustration.inline.svg'
<Illustration className="example" />
盖茨比官方指南中的所有信息
就这样做...
import YourDesiredName from 'path/to/file.svg'