【发布时间】:2020-07-24 07:15:20
【问题描述】:
我见过以下解决方案:
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 中使用这个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.js 或 gatsby-config.js?
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" />
来自official Gatsby guide的所有信息
【讨论】:
就这样吧……
import YourDesiredName from 'path/to/file.svg'
【讨论】: