简体   繁体   English

将 SVG 图像添加到 React 项目的简单方法

[英]Simple way to add SVG images into a React project

I'm using file loader and can load pngs just fine.我正在使用文件加载器,可以很好地加载 png。 I'm doing import myImage from "../../path/image.svg" and then <img src={myImage}/> .我正在import myImage from "../../path/image.svg"然后<img src={myImage}/> When I use the developer tools and click on the SVG I'm trying to include, I get a page with a message like:当我使用开发人员工具并单击我尝试包含的 SVG 时,我收到一个页面,其中包含如下消息:

"Error on line 1 at column 1: Document is empty 

Below is a rendering of the page up to the first error."

Has anyone seen this error before and if so what can be done about it?有没有人以前见过这个错误,如果有的话可以做些什么?

If you look at the file loader docs there is no mention of being able to load svg files.如果您查看文件加载器文档,则没有提到能够加载 svg 文件。

You need to use a specialised loader.您需要使用专门的装载机。 Here are webpack docs for one svg loader but there are plenty of others.这是一个 svg 加载器的 webpack文档,但还有很多其他的。

我发现了@svgr/webpack ,有了它,您可以像模块一样导入SVG ,然后将它们用作组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM