javascript - 找不到模块 React require

标签 javascript reactjs

我收到以下错误:错误:找不到模块“./img/grpd/IMG_2812.JPG”

我基本上是在尝试迭代源图像中的图像目录并显示图像。

我注意到如果我更改以下行

var filePath = './img/grpd/IMG_' + i + '.JPG';

var filePath = './img/grpd/IMG_2803.JPG';

页面呈现得很好。

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

  class ImageWrapper extends React.Component {

    render() {
      // require expects a string
      return <img src={require("" + this.props.imageSrc)} />;
    }
  }

  class CartoonPage extends React.Component {

    render() {
      var cartoons = [];
      for (var i = 2803; i< 2817; i++) {
        var filePath = './img/grpd/IMG_' + i + '.JPG';
        var img = <ImageWrapper key={i} imageSrc={filePath}/>;
        cartoons.push(img);
      }
      return cartoons;
    }
  }

  ReactDOM.render(
    <CartoonPage />,
    document.getElementById('root')
  );

最佳答案

如果您设置为使用 webpack(这对于 React 项目来说非常典型),那么您不能使用完全动态导入。

It is not possible to use a fully dynamic import statement, such as import(foo). Because foo could potentially be any path to any file in your system or project.

https://webpack.js.org/api/module-methods/#dynamic-expressions-in-import

您编写的代码不会将您的图像包含在 bundle 中。当您的应用运行时,它所需的文件根本不在您的应用期望的位置。

解决方案是在导入中使用路径的一部分。这将为 webpack 提供关于应该包含哪些内容的提示。请注意,它将使用模式匹配,因此可能包含比 bundle 中实际需要的文件多得多的文件。您可以使用魔术注释来创建“包含”和“排除”模式,以进一步细化 bundle 中包含的文件。

var cartoons = [];
for (var i = 2803; i< 2817; i++) {
    var img =
        <ImageWrapper key={i}
            imageSrc={require(
                /* webpackExclude: /pattern_to_exclude/ */
                /* webpackChunkName: "cartoon-images" */
                // preload because you'll need these during the current navigation:
                /* webpackPreload: true */
                `./img/grpd/IMG_${filePath}.JPG`
            )}
        />;
    cartoons.push(img);
}

关于javascript - 找不到模块 React require,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60470682/

相关文章:

javascript - 如何在 chrome 开发人员工具时间轴中获得可重现的节点数?

javascript - 在 NEXTjs 中使用 React-Moveable 时遇到问题 : TypeError: Cannot read property 'userAgent' of undefined

javascript - 在草案 js 中实现表格支持

reactjs - 更改 MUI 中的 Appbar 背景颜色

javascript - ReactJS 与 Jquery 数据表问题

javascript - 使用 JavaScript 动态更改背景颜色

javascript - jsx 中的 React 组件未渲染为 html

javascript - 在 NodeJS 中创建 HTTPS 客户端

javascript - 代码可以在 IE 中运行,但不能在 FF 中运行

javascript - 一旦 promise 得到解决,如何在 catch 中传递错误?