Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using file-loader and html-loader in webpack the src attr of image is '[object Module]'

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...

like image 944
Nelson Avatar asked Nov 30 '19 08:11

Nelson


People also ask

How do I import an image into webpack?

If you are using webpack, then the most stable way would be to import the image in TS/JS using https://webpack.js.org/loaders/url-loader/, and bind the import (depending on the loader configuration it is either b64 encoded data url, or a simple string url) to the src of img .

How does webpack file-loader work?

Webpack goes through all the import ed and require d files in your project, and for all those files which have a . svg extension, it uses as an input to the webpack file loader. For each of these files, the file loader emits the file in the output directory and resolves the correct URL to be referenced.

What is HTML loader used for?

By default, html-loader generates JS modules that use the ES modules syntax. There are some cases in which using ES modules is beneficial, such as module concatenation and tree shaking.

What is webpack HTML?

The HtmlWebpackPlugin simplifies creation of HTML files to serve your webpack bundles. This is especially useful for webpack bundles that include a hash in the filename which changes every compilation.


2 Answers

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:

  • file-loader release history
  • relevant github issue
like image 54
MrSegFaulty Avatar answered Nov 02 '22 16:11

MrSegFaulty


{
    test: /\.(png|jpe?g|gif)$/i,
    loader: 'file-loader',
    options: {
        name: '[name][hash].[ext]',
        outputPath: 'images',
        esModule: false,
    },
},
like image 22
ali Avatar answered Nov 02 '22 18:11

ali