I'm trying to set up a modern vanilla web starter with Webpack.
I got stuck when I added webpack-html-loader
and html-loader
. Here's what happens...
- When I make use of an
img
tag in the entryindex.html
file, with ansrc
attribute like this (./imgs/image.png
), thesrc
attribute in thedist
folder is replaced with[object Module]
. But when I remove the dot before theuri
(./imgs/image.png
to/imgs/image.png
), thesrc
output in thedist
folder is exactly the same as that of thesrc
. This doesn't reference the image I want to include. - Since the
src
value of the webpack output is exactly the same as the source, I try to be crude and use theuri
to the image in the output folder like so/dist/img/image.png
. This works, but it's not a great experience. I would love to use auri
to my image in thesrc
folder and have webpack replace it withdist
at build time. Is this possible?
Here's what my file structure looks like after npm run build
- dist
- imgs
- image.png
- index.html
- main.js
- node_modules
- src
- index.html
- imgs
- image.png
- package.json
- package-lock.json
- webpack.config.js
Here's my webpack.config.js
const HTMLWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const path = require("path");
module.exports = {
module: {
rules: [
{
test: /\.(html)$/,
use: [
{
loader: "html-loader",
options: {
minimize: false
}
}
]
},
{
test: /\.(png|jpe?g)$/,
use: [
{
loader: "file-loader",
options: {
outputPath: "imgs",
publicPath: "imgs",
name: "[name].[ext]"
}
}
]
}
]
},
plugins: [
new HTMLWebpackPlugin({
template: path.resolve(__dirname, "src/index.html")
}),
new CleanWebpackPlugin()
]
};
I made a repo of it here
Thanks a lot for your time
Update (02-01-2020)
Someone in the comment pointed out a solution to the problem. (When i using file-loader and html-loader in webpack. The src attr of image gonna be like '[object Module]')
The solution is to set the esModules
object to false
in the file-loader
rule like so
{
test: /\.(png|jpe?g)$/,
use: [
{
loader: "file-loader",
options: {
// Here!!!
esModule: false,
outputPath: "images",
publicPath: "images",
name: "[name].[ext]"
}
}
]
}