Reputation: 6675
I'm trying to understand how webpack is working. For this I created a very simple example:
Folder structure
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:
Does any one know why webpack cannot show the image?
Upvotes: 0
Views: 1542
Reputation: 5422
You need to use html-loader
https://webpack.js.org/loaders/html-loader/ so that it require()
s for you every url
from <img src="<url>">
correctly at compile time, otherwise your browser will try to access the path it cannot reach during runtime.
Also when using html-loader
, since it will require img
urls for you, you will need a specific loader that understands image format, for which you can use https://webpack.js.org/loaders/url-loader/ or https://webpack.js.org/loaders/file-loader/
Otherwise you will need to copy all your images to a dist folder where you can access them publicly during runtime in browser from your html without html-loader
or require
calls. But the copying itself can be done again through another loader https://webpack.js.org/plugins/copy-webpack-plugin/ .
And still you cannot access the compile level paths like ../src
, since when webpack is running it's compiling everything into a final public folder where you only have your main js file and all of it's require()
ed dependencies that are put into the same final(dist
) folder based on the rules from loaders
or plugins
property in webpack config.
Upvotes: 1