incorrect resource path when importing image url when using asset/resource

23 hours ago 5
ARTICLE AD BOX

The image is being produced in ~/Documents/restaurant-page/dist/images/52e944639d832ccc4639.png but the URL imported in javascript is /home/amanr/Documents/restaurant-page/distimages/52e944639d832ccc4639.png . There is a / missing between dist and images.

The image fails to render when opening the html file by itself but it renders correctly when opening through the server setup by webpack-dev-server. Any idea why this happens? Would this impact something if I host it?

Webpack Config:

import path from 'node:path'; import HtmlWebpackPlugin from "html-webpack-plugin"; const __dirname = import.meta.dirname; export default { entry: "./src/index.js", output: { publicPath: path.resolve(__dirname, "dist/"), filename: "index.bundle.js", assetModuleFilename: 'images/[hash][ext][query]', }, mode: "development", plugins: [new HtmlWebpackPlugin({ template: path.resolve(__dirname, "src/template.html"), filename: 'index.bundle.html' })], module: { rules: [ { test: /\.(?:js|mjs|cjs)$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { targets: "defaults", presets: [ ['@babel/preset-env'] ] } } }, { test: /\.css$/i, use: ["style-loader", "css-loader"], }, { test: /\.(png|svg|jpg|jpeg|gif|webp)$/i, type: 'asset/resource' }, ], }, devServer: { static: { directory: path.resolve(__dirname, 'dist'), }, port: 3000, open: true, hot: true, compress: true, historyApiFallback: true, } };

Import:

import customImg from '../images/custom.png'; export function loadHomePage() { const heroDiv = document.createElement('div'); heroDiv.classList.add('hero', 'min-h-screen'); console.log(customImg); heroDiv.style.backgroundImage = `url(${customImg})`; .... }
Read Entire Article