Search code examples
javascriptcsswebpackwebpack-dev-serverwebpack-file-loader

Webpack file-loader emits png with different name than the one referenced in emitted bundle.js


I'm trying to find my way around Webpack file loader with a simple practice project. I've put an icon.pngin ./src, along with index.js and style.css (as per https://webpack.js.org/guides/asset-management/). After running webpack (via yarn build or watch scripts) I get no errors, and actually get a file called a0cadc7b7cbb7dd92495c1d9567c52e7.pngin ./dist. However, the file referenced by the resulting bundle is different when checked in the dev-tools (dista0cadc7b7cbb7dd92495c1d9567c52e7.png) and thus it's not loaded at all.

This is really puzzling... Any ideas to solve this issue?

webpack.config.js

const path = require("path");

module.exports = {
  mode: 'development',
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: 'dist',
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader'
        ],
      },
      {
        test: /\.(png|jpg|svg|gif)$/,
        use: [
          'file-loader'
        ],
      },
    ],
  },
};

index.js

import sayHello from './hello';
import './style.css';
import icon from './icon.png';
sayHello();

function component() {
  const element = document.createElement("div");
  element.innerHTML = "Hello from webpack!";
  element.classList.add("hello");


  const myIcon = new Image();
  myIcon.src = icon;
  element.appendChild(myIcon);
  return element;
}

document.body.appendChild(component());

style.css

.hello {
  color: red;
  background-image: url('./icon.png');
}

Also: package.json

{
  "name": "webpack-practice",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "build": "webpack --progress -p",
    "watch": "webpack --progress --watch",
    "server-c9": "webpack-dev-server --host 0.0.0.0 --port 8080 --progress"
  },
  "license": "MIT",
  "private": true,
  "devDependencies": {
    "css-loader": "^3.4.0",
    "file-loader": "^5.0.2",
    "style-loader": "^1.1.2",
    "webpack": "^4.41.5",
    "webpack-cli": "^3.3.10",
    "webpack-dev-server": "^3.10.1"
  }
}

Update: I commented out publicPath in webpack.config.js and got it to work... but without that I lost Live Reloading in webpack-dev-server... Which is now my first subject for this unexpected behavior...


Solution

  • It looks like you are using publicPath in webpack config wrongly. You could just remove it for now or replace to default value "./"

    Please read this for more details