百度搜索了一下 SVGR ,结果没搜索到一条相关的内容。因此我决定写一系列关于 SVGR 教程的文章,本文是第一篇,SVGR 入门简介篇。
svgr 是一个将SVG转换为React组件,svgr 由 JavaScript 实现。整个文档也非常的小,目前最新版本为v0.5.0,已开源在github上。
svgr 官网地址:https://github.com/smooth-code/svgr。截止发稿前,svgr 已获得上千的 star。
svgr 包含一下核心关键词:svg2react、svg-to-react、svg、svgo、react、react-svg、react-svg-creator、svg-react、webpack-loader、webpack、inline-svg。

安装svgr
npm install svgr
基本用法
看一个icon.svg例子:
<?xml version="1.0" encoding="UTF-8"?>
<svg width="48px" height="1px" viewBox="0 0 48 1" version="1.1"
xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 46.2 (44496) - http://www.bohemiancoding.com/sketch -->
<title>Rectangle 5</title>
<desc>Created with Sketch.</desc>
<defs></defs>
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="19-Separator" transform="translate(-129.000000, -156.000000)" fill="#063855">
<g id="Controls/Settings" transform="translate(80.000000, 0.000000)">
<g id="Content" transform="translate(0.000000, 64.000000)">
<g id="Group" transform="translate(24.000000, 56.000000)">
<g id="Group-2">
<rect id="Rectangle-5" x="25" y="36" width="48" height="1"></rect>
</g>
</g>
</g>
</g>
</g>
</g>
</svg>
运行SVGR:
svgr --no-semi --icon --replace-attr-value "#063855=currentColor" icon.svg
最后被转换成了React 代码:
import React from "react"
// ;www.xttblog.com
const SvgComponent = props => (
<svg width="1em" height="1em" viewBox="0 0 48 1" {...props}>
<path d="M0 0h48v1H0z" fill="currentColor" fillRule="evenodd" />
</svg>
)
export default SvgComponent
svgr 还有很多开箱即用的功能,我们下章再说。

: » svgr 简介
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/tech/aiops/251324.html