1

I Launch project with create-react-app. No response even if img path is specified on React APP. Image is displayed when import statement is used

// not working (1)
<img src={"../img/hoge.png"} />;

//working (2)
import Hoge from "../img/hoge.png";

<img src={Hoge} />

I want to user pattern (1). Please tell me the solution orz......

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
555jiki
  • 31
  • 3
  • 1
    I don't think the first way is possible. I think the reason is that Webpack needs the imports at the top of each file in order to work correctly. But someone else may have more information. –  Jun 07 '20 at 13:49
  • Why do you want to use solution 1 instead of 2? Solution 2 is what is supported by create-react-app and webpack out of the box. – Håken Lid Jun 07 '20 at 14:15

2 Answers2

1

Use require for dynamic imports, path like "../img/hoge.png" is not available in runtime because Webpack generates data URI in build time.

import hoge from '../img/hoge.png'; // Tell webpack this JS file uses this image
console.log(hoge); // /hoge.84287d09.png

// For dynamic imports
<img src={require("../img/hoge.png")}  />

See Adding images in CRA docs.

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
0

If you have a list of potential images at build time, you can use the dynamic import function to load them, although this will return a promise like so:

export class ImageLoader extends React.Component {
    constructor(props: any){
        super(props);
        this.state = {
            imagePath: undefined
        };
    }
    render() {
        if(this.state.imagePath)
            return <img src={this.state.imagePath}  />; // Render the image
        import(/* webpackMode: "eager" */`../imgs/${this.props.imageName}.png`) // Bundle all paths of images into the bundle
            .then((imagePath: string) => {
                this.setState({ imagePath}); // Set the new state with the loaded image path
            });
        return null; // Don't render anything right now since the image hasn't loaded yet.
    }
}

This will bundle ALL png images under the imgs directory, use a switch statement with all possible names if that is too much.

See Webpack Documentation and How does Dynamic Import in webpack works when used with an expression?

Elias Schablowski
  • 2,619
  • 9
  • 19