Webpack File-Loader Outputs [Object Module]

Webpack file-loader outputs [object Module]

Per the file-loader docs:

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

It seems that webpack resolves ES module require() calls to an object that looks like this: {default: module}, instead of to the flattened module itself. This behavior is somewhat controversial and is discussed in this issue.

Therefore, to get your src attribute to resolve correctly, you need to be able to access the default property of the exported module. If you're using a framework, you should be able to do something like this:

<img src={require('assets/logo.png').default}/> <!-- React -->
<!-- OR -->
<img src="require('assets/logo.png').default"/> <!-- Vue -->

Alternatively, you can enable file-loader's CommonJS module syntax, which webpack will resolve directly to the module itself. Set esModule:false in your webpack config.

webpack.config.js:

 {
test: /\.(png|jpe?g|gif)$/i,
use: [
{
loader: 'file-loader',
options: {
esModule: false,
},
},
],
},

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

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


Related Topics



Leave a reply



Submit