在create-react-app中引入本地图片资源

在create-react-app中引入本地(svg/png/jpg)资源

因为之前都是做的Vue,引用本地资源之类的操作都是和html一样,直到今天修改React项目的需求才发现,这好像不一样;
例如我在项目中引用本地的一个png<img src='@images/logo.png' />,再打开页面,发现图片并没有显示,控制台也没有报错。后台查了半天,怪自己太菜。。。

官方文档中表示:

You can import a file right in a JavaScript module. This tells Webpack to include that file in the bundle. Unlike CSS imports, importing a file gives you a string value. This value is the final path you can reference in your code, e.g. as the src attribute of an image or the href of a link to a PDF.

之后研究了一下,找到了集中解决办法

  1. 使用import引入
1
2
3
import imgs from '@/images/logo.png'

<img src={imgs} />

这样页面就可以正常显示,但是因为是import引入,所以只能是需要什么就要import什么

  1. 使用require.context

这种解决方法的思路就是全部引入所需要的资源文件,然后按需要放到页面上,不需要挨个写import…这样的语句,因为感觉全部引入不太好,没有太深入了解,文章末尾放的一个链接好像有解决方案!

  1. 直接使用webpack的require
1
<img src={require('@images/logo.png')} />

这样相较于第一种方法的好处在于我们可以动态按照需要引入不同的资源图片,例如

1
2
3
let svg = 'logo'

<img src={require('@images/' + svg + '.png')} />

这样如果是一个命名规律的资源文件,那么就可以委婉的用这种方法来引用本地文件。

另外:

在掘金中看到一篇图标使用新姿势-react按需引用svg实现
还没来及看,感觉好高级,等看完补上