https://www.pluralsight.com/resources/blog/guides/how-to-load-svg-with-react-and-webpack
Introduction 介绍

As developers, we want all our images to look sharp and nice, even when we scale them up. To achieve the level of sharpness we want for our websites using bitmap images, such as JPEGs, GIFs, and PNGs, we have to increase file size, which greatly impacts the performance of the website. Vector images, however, looks crisp regardless of screen resolution and are relatively small in size.作为开发人员,我们希望所有图像看起来清晰漂亮,即使我们放大了它们。为了使使用位图图像(例如 JPEG、GIF 和 PNG)的网站达到我们想要的清晰度水平,我们必须增加文件大小,这会极大地影响网站的性能。然而,无论屏幕分辨率如何,矢量图像看起来都很清晰,并且尺寸相对较小。

In this guide, we’ll learn about Scalable Vector Graphics (SVG)
and explore the standard way of importing SVG in a React
Application bundled with Webpack
.在本指南中,我们将了解可扩展矢量图形 (SVG),并探索在与 Webpack 捆绑的 React 应用程序中导入 SVG 的标准方法。

What is SVG? 什么是 SVG?

SVG is an XML-based markup language for describing two-dimensional-based vector graphics. SVG is essentially to graphics what HTML is to text.SVG 是一种基于 XML 的标记语言,用于描述基于二维的矢量图形。 SVG 之于图形本质上就像 HTML 之于文本。

SVG images basically take the place of traditional images in other formats like JPEG, PNG, TIFF or GIF.SVG 图像基本上取代了 JPEG、PNG、TIFF 或 GIF 等其他格式的传统图像。

Advantages of using SVG over other image formats are:与其他图像格式相比,使用 SVG 的优点是:

SVG images can be searched, indexed, scripted, and compressedSVG 图像可以被搜索、索引、脚本化和压缩

SVG images are scalable SVG 图像是可缩放的

SVG can be created and edited with any text editor可以使用任何文本编辑器创建和编辑 SVG

SVG images do NOT lose quality even if they are resized or zoomed即使调整大小或缩放 SVG 图像也不会损失质量

SVG images can be animated, unlike other traditional image formats与其他传统图像格式不同,SVG 图像可以动画化

Let’s take a closer look at how to use SVG images. The xml code below creates a rectangle:让我们仔细看看如何使用 SVG 图像。下面的 xml 代码创建一个矩形:

rectangle.svg 矩形.svg

<svg version="1.1" baseProfile="full" width="300" height="200" xmlns="http://www.w3.org/2000/svg"> <rect width="100%" height="100%" fill="green" /> </svg>

The most basic way to embed an SVG via an element is to reference it in the src attribute, as you’d expect. You will need a height or a width attribute (or both if your SVG has no inherent aspect ratio).通过 元素嵌入 SVG 的最基本方法是在 src 属性中引用它,正如您所期望的那样。您将需要高度或宽度属性(如果您的 SVG 没有固有的宽高比,则需要两者)。

<img src="rectangle.svg" alt="A Rectangle Image with SVG" height="45px" width="45px" />

Usage with React 与 React 一起使用

The easiest way of implementing an SVG in a React app is as follows:在 React 应用程序中实现 SVG 最简单的方法如下:

const App = () => <img src="/images/rectangle.svg" alt="A Rectangle Image with SVG" />;

However, in most cases, SVGs are usually pretty small, and in these cases we are better off inlining the images as data URLs, limiting the amount of requests a browser has to make to the server in order to render the webpage.然而,在大多数情况下,SVG 通常非常小,在这些情况下,我们最好将图像内联为数据 URL,从而限制浏览器为了呈现网页而必须向服务器发出的请求量。

To transform an SVG image into a Data URL, we will need an appropriate webpack loader in our bundler. The most common webpack loader for this is svg-url-loader
, which can be added as shown below:要将 SVG 图像转换为数据 URL,我们的捆绑器中需要一个适当的 webpack 加载器。最常见的 webpack 加载器是 svg-url-loader ,可以如下所示添加:

npm i svg-url-loader --save-dev

Add to webpack.config.js:添加到 webpack.config.js :

const webpack = require('webpack'); module.exports = { entry: './src/index.js', module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: ['babel-loader'], }, { test: /\.svg$/, use: [ { loader: 'svg-url-loader', options: { limit: 10000, }, }, ], }, ], }, ... };

Import the file into your React app:将文件导入到您的 React 应用程序中:

import rectangle from 'images/rectangle.svg'; const App = () => <img src={rectangle} alt="" />;

The output in the DOM will be something like this:DOM 中的输出将如下所示:

<img src="ebbc8779488b4073081931bd519478e8.svg" alt="" />

You can check out svg-url-loader
for more on the configurations.您可以查看 svg-url-loader 以了解有关配置的更多信息。

In the examples above, the svg-url-loader can only be used in the traditional way, including images in a web application such as background-image or content. The next question is how to use an SVG image as a React Component.在上面的示例中, svg-url-loader 只能以传统方式使用,包括 Web 应用程序中的图像,例如 background-image 或 content 。下一个问题是如何使用 SVG 图像作为 React 组件。

SVG as a React ComponentSVG 作为 React 组件

The solution is not farfetched. We’ll need the help of another awesome webpack loader called svgr
, which, according to the website, transforms the SVG into a ready-to-use React component.解决方案并非牵强。我们需要另一个名为 svgr 的出色 webpack 加载器的帮助,根据该网站的说法,它将 SVG 转换为随时可用的 React 组件。

So how do we use this awesome tool? Lets start by updating our webpack.config.js:那么我们如何使用这个很棒的工具呢?让我们首先更新我们的 webpack.config.js :

const webpack = require('webpack'); module.exports = { entry: './src/index.js', module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: ['babel-loader'], }, { test: /\.svg$/, use: ['@svgr/webpack'], }, ], }, ... };

Then we can install it as a dev-dependency in the usual way:然后我们可以按照通常的方式将其安装为开发依赖项:

npm install @svgr/webpack --save-dev

Once you start your application, Webpack will do its thing and you don’t need to worry about your SVGs anymore. You can put your SVG files anywhere in your src/ folder and import them wherever you need them as React components.一旦你启动你的应用程序,Webpack 就会做它的事情,你不需要再担心你的 SVG。您可以将 SVG 文件放在 src/ 文件夹中的任何位置,并将它们作为 React 组件导入到任何需要的地方。

Lastly, import the file in your React app:最后,将文件导入到您的 React 应用程序中:

import Image from 'path/image.svg'; const App = () => ( <div> <Image /> </div> )

This method is generally referred to as inline-svg.这种方法通常被称为 inline-svg 。

A lightweight alternative solution to svgr is react-svg-loader
.svgr 的一个轻量级替代解决方案是react-svg-loader。

const webpack = require('webpack'); module.exports = { entry: './src/index.js', module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: ['babel-loader'], }, { loader: 'react-svg-loader', options: { jsx: true // true outputs JSX tags } } ], }, ... };

And install as usual: 并像往常一样安装:

npm install react-svg-loader --save-dev

For the most part, we do not want all our SVG files to be loaded as a React components. We could combine the above methods depending on the use case. All we have to do is update our webpack configuration.大多数情况下,我们不希望所有 SVG 文件都作为 React 组件加载。我们可以根据用例组合上述方法。我们所要做的就是更新我们的 webpack 配置。

The example below uses svgr and url-loader
, a webpack loader which transforms files into base64 URIs.下面的示例使用 svgr 和 url-loader ,这是一个将文件转换为 base64 URI 的 webpack 加载器。

const webpack = require('webpack'); module.exports = { entry: './src/index.js', module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: ['babel-loader'], }, { test: /\.svg$/, use: ['@svgr/webpack', 'url-loader'], }, ], }, ... };

The usage in your application would look this:您的应用程序中的用法如下所示:

import imageUrl { ReactComponent as Image } from 'path/image.svg'; const App = () => ( <div> <img src={imageUrl} alt="" /> <Image /> </div> )

Conclusion 结论

This guide has provided you with a quick intro into how to import SVG into your React Application using webpack as the bundler.本指南向您快速介绍了如何使用 webpack 作为捆绑器将 SVG 导入到 React 应用程序中。

Here are a few other resources on SVG and its numerous applications:以下是有关 SVG 及其众多应用程序的一些其他资源:

Getting Started with SVG SVG 入门

Ultimate Guide to SVG SVG 终极指南