cannot import image with create-react-app

前端 未结 5 1380
悲&欢浪女
悲&欢浪女 2021-02-18 21:43

I\'m using create-react-app, and I am struggling to load images. I am following the instructions as specified here, but I keep seeing the following error:



        
相关标签:
5条回答
  • 2021-02-18 22:11

    I had the same problem and was able to solve with a require statement.

    const photo = require('./party.png');

    and then in your component use that like:

    render() {
        return (
            <img src={photo}/>
    

    also see this post Displaying a static image using React, Typescript and Webpack

    0 讨论(0)
  • 2021-02-18 22:16

    By default, Create-React-App uses url-loader for files with size 10000 bytes

    that works fine in the development environment, but in production reduce error.

    For a production environment, you should change the value for the limit of bytes in order to enforce webpack use file-loader instead.

    If you have to eject your app modify webpack.config.prod.js file and change the limit of url-loader to 10 and will work as well

    {
     test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
     loader: require.resolve('url-loader'),
     options: {
     limit: 10,
     name: 'static/media/[name].[hash:8].[ext]',
    },
    
    0 讨论(0)
  • 2021-02-18 22:26

    You can simply use something like this:

    render() {
      // Note: this is an escape hatch and should be used sparingly!
      // Normally we recommend using `import` for getting asset URLs
      // as described in “Adding Images and Fonts” above this section.
      return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />;
    }
    

    Quoted directly from CRA docs

    0 讨论(0)
  • 2021-02-18 22:31

    As @archae0pteryx proposed it is much better to separate pictures from the code, so the project public folder should be used instead of src.

    Here is how it works with css:

    1. copy 'img.bmp' into /public
    2. inside .css file/class: background-image: url('/img.bmp');
    0 讨论(0)
  • 2021-02-18 22:32

    Are you sure you've got the correct path? Also when you import an image via css (as is done in the example you mentioned) you need to give a path relative to the public folder and not the src folder. I have run into this problem several times.

    An example using import:

    import Image from './img.png'
    ...
    // react example
    ...
    render() {
        return (
            <img src={Image}/> // notice the curly
    ...
    

    and not

    <img src="Image"/>
    
    0 讨论(0)
提交回复
热议问题