Webpack动态导入方法返回空数组而不是reactjs中的文件,如何解决? [英] Webpack dynamic import method returns empty array instead of files in reactjs, How to solve?

查看:101
本文介绍了Webpack动态导入方法返回空数组而不是reactjs中的文件,如何解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Reactjs中导入和使用图像?
我已经从文件夹导入了所有图像,但它没有返回带链接的数组。
检查这个。

How to import and use images in Reactjs? I have imported all images from a folder but it does't return array with links. check this.

    function importAll(r) {
    return r.keys().map(r);
  }
    const images = importAll(require.context('./', false, /\.(png|jpe?g|svg)$/));
    console.log(images);

检查控制台的屏幕截图:

Check this screenshot of console:

请帮助我!

文件夹结构:

--src>
  --components>
      Projects.jsx
  --img>
       images

我想在Projects组件中导入它。
但是,怎么做?

I am trying to import it in Projects component. but, How to do this?

import React from 'react';
import '../App.css';

function importAll(r) {
    return r.keys().map(r);
}

const images = importAll(require.context('./', false, /\.(png|jpe?g|svg)$/));
console.log(images);

请帮助加载所有图像并使用它们。

Please help in load the all images and use them.

推荐答案

正确的要求是:

importAll(require.context('./img', false, /\.(png|jpe?g|svg)$/));

来自docs:

require.context('./test', false, /\.test\.js$/);
// a context with files from the test directory that can be required with a request endings with `.test.js`.


require.context('../', true, /\.stories\.js$/);
// a context with all files in the parent folder and descending folders ending with `.stories.js`.

这篇关于Webpack动态导入方法返回空数组而不是reactjs中的文件,如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆