I am developing a vanilla Javascript project for the first time using Webpack.
This is successfully compiled in both "production" and "development" mode, but instead of the images, it displays the broken image icon.
This is the project folder structure:
This is the webpack.config.js file:
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
module.exports = {
entry: {
main: "./src/js/index.js",
},
output: {
path: path.resolve(__dirname, "dist"),
filename: "[name].bundle.js",
clean: true,
},
plugins: [
new HtmlWebpackPlugin({
title: "Life Quality App",
}),
],
module: {
rules: [
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
{
test: /\.(eot|svg|ttf|woff|woff2|png|jpe?g|gif)$/i,
type: "asset/resource",
use: {
loader: "img-optimize-loader",
options: {
compress: {
mode: "lossless",
},
},
},
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
type: "asset/resource",
use: {
loader: "url-loader",
options: {
name: "fonts/[name].[ext]",
},
},
},
{
test: /\.js$/i,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["@babel/preset-env"],
},
},
},
],
},
optimization: {
minimizer: [new CssMinimizerPlugin()],
},
devServer: {
static: path.resolve(__dirname, "dist"),
open: true,
},
};
These are the javascript file example where I import the image:
rendSearchUI.js
import greenCityImg from "../assets/images/test.jpg";
const renderSearchUI = () => {
const body = document.body;
const appContainer = document.createElement("div");
const appTitle = document.createElement("h1");
const img = document.createElement("img");
img.src = greenCityImg;
appContainer.classList.add("app-container");
appTitle.classList.add("app-title");
appTitle.textContent = "LIFE QUALITY APP";
appContainer.append(appTitle, img);
body.appendChild(appContainer);
};
export default renderSearchUI;
index.js
import "../styles/main.css";
import renderSearchUI from "./renderSearchUI.js";
window.addEventListener("DOMContentLoaded", () => {
renderSearchUI();
});
If I run console.log(img.src) it displays an incorrect path: "http://localhost:8080/c744d32a4afed775625c.jpg"
How can I fix that?
Thank you so much!
