简体   繁体   中英

Cannot find module React require

I get the following error: Error: Cannot find module './img/grpd/IMG_2812.JPG'

I'm basically trying to iterate through the images directory in source and display images.

I noticed if I change the following line

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

to

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

the page renders just fine.

 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') );

If you are setup to use webpack (which is pretty typical for React projects), then you can't use completely dynamic imports.

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

You code, as-written, will not include your images in the bundle. When your app runs, the files it needs simply aren't where your app expects them to be.

The solution is to use a portion of the path in the import. This will give webpack a hint as to what should be included. Note that it will use pattern matching and, thus, may include far more files than are actually needed in the bundle. You can use magic comments to create "include" and "exclude" patterns to further refine the files are included in the 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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