Webpack dev-server doesn't show the image

Hi,
I’m trying to understand how webpack is working. For this I created a very simple example:

webpack.config.js

const path = require('path');

module.exports = {
  entry: ['./src/index.js'],
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
  },
  devServer: {
    contentBase: path.resolve(__dirname, 'dist'),
    publicPath: '/',
  },
  devtool: 'source-map',
};

index.html

<body>
  <div>
    <img src="../src/images/lion.png" alt="">
  </div>

  <script src="./bundle.js"></script>
</body>

As you can see the index.html is inside the dist folder. If I open the index.html in browser, it shows the images. But if I run the dev-server, it starts the browser, shows the index.html but cannot find the image. And the console shows this error:
Failed to load resource: The server responded with a status of 404. lion.png

Does any one know why webpack cannot show the image?

I’m not 100% sure, but when you are running the dev-server, the file arrangement is different than what you see in your project structure. Dev-server only looks at the contents of your dist folder. You will not have access to any folders outside of it unless they are created inside the dist folder as well.

Your browser doesn’t have that limitation when opening index.html directly from the file system. That’s why pointing the browser directly to index.html works.

:newspaper_roll:

1 Like