18

I am doing a project with webpack4 from scratch. But when I try to display an image in an HTML file, I face a weird problem: After npm run build, the src of image tag is built as <image src="[object Module]". The HTML part is:

<img src="images/main_background.jpg">

The webpack.config.js is this :

   // ignore ...
   {
    test: /\.html$/,
    use: [
       {loader: 'html-loader'}
    ]
   },
   {
      test: /\.(jpeg|jpg|png)$/,
      use: [
        'file-loader'
      ]
  }


And the version of these two loaders:

"file-loader": "^5.0.2",
"html-loader": "^0.5.5",

I can't figure out what the issue is...

stellr42
  • 3,365
  • 2
  • 21
  • 33
Nelson
  • 209
  • 2
  • 7

3 Answers3

29

Try adding esModule: false option to file-loader like so:

  ...
  {
    test: /\.(jpeg|jpg|png)$/,
    use: [
      loader: 'file-loader',
      options: {
        esModule: false
      }
    ]
  }
  ...

Same applies to url-loader.

esModule option has been introduced in file-loader in version 4.3.0 and in 5.0.0 it has been set to true by default which can be a breaking change.

Sources:

MrSegFaulty
  • 535
  • 6
  • 10
3
{
    test: /\.(png|jpe?g|gif)$/i,
    loader: 'file-loader',
    options: {
        name: '[name][hash].[ext]',
        outputPath: 'images',
        esModule: false,
    },
},
M Hamza Javed
  • 1,269
  • 4
  • 17
  • 31
ali
  • 31
  • 1
3

If you're lazy, you can manually access the image path from that Module object by way of the default property:

const imgPath = require('path/to/img.jpg').default;

That'll give you the image's exact path after it's been prepped for distribution, eg:

/images/logo-192.png?88bf116f524693c599897adae2bb688b

If you're using a framework like Vue, you can just pop it straight into the src attribute:

<img :src="require('path/to/img.jpg').default">
Jans Rautenbach
  • 394
  • 4
  • 13