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("https://stackoverflow.com/questions/59070216/assets/logo.png").default}/> <!-- React -->
<!-- OR -->
<img src="require("https://stackoverflow.com/questions/59070216/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,
            },
          },
        ],
      },

Leave a Comment