1

I'm trying to load in an image file that's contained within my src folder. I'm loading it into App.js like so:

import React, { Component } from 'react';
import './App.css';
import logo from 'images/logo.png';

class App extends Component {
  render() {
    return (
        <header>
            <img src={logo} alt={"logo"}/>
        </header>
    );
  }
}

export default App;

Unfortunately, I get this error:

./src/App.js
Module not found: Can't resolve 'logo.png' in '/src'

I arrived at this code with this Stack Overflow answer: https://stackoverflow.com/a/35454832/7386637 ..but what am I doing wrong here?

rpivovar
  • 3,150
  • 13
  • 41
  • 79

1 Answers1

0

If you want to be using file paths like this, you need to add a resolve property to your webpack config, like so

  resolve: {
    modules: [path.resolve(__dirname, 'PATH_THAT_HOLDS_YOUR_IMAGE_DIRECTORY')]
  },

So for example if your images live in project/assets/images/ and your webpack config lives in project/ then in the above you would replace PATH_THAT_HOLDS_YOUR_IMAGE_DIRECTORY with assets.

Using import logo from 'images/logo.png'; would work then. (Reminder that you need to restart your dev-server in order for changes in webpack config to take effect)

Otherwise, relative paths will work fine, as mentioned.

Dimitris Karagiannis
  • 8,942
  • 8
  • 38
  • 63