The solution of path error output to [object module] when file loader packages image files

Time:2020-11-28

Recently, I learned to use webpack4.0 to build Vue scaffold by myself. In the process of building, I stepped on many pits. When I used file loader to package image files, I encountered the following problems.

This is my webpack configuration item for processing packaged images:


...
module: {
 rules: [
 ...
 {
  test: /\.(jpe?g|png|gif|svg)$/i,
  use: [
  {
   loader: 'url-loader',
   options: {
   limit: 10000,
   name: '[name].[ext]',
   outputPath: 'imgs/'
   }
  }
  ]
 },
 ...
 ]
}
...

This configuration is similar to the current online tutorial. useurl-loaderCompile the image file, output to the IMGs folder, at first glance, there is no problem, I believe you think so.

However, after the webpack is built, it will be found that the images quoted on the page cannot be displayed normally

Picture reference error

Open the console and you will find that the path of all the pictures has changed[object module]

object module

After a lot of hard exploration, we finally found the corresponding problems in stack overflow

The following is my translation:

By default, the file loader generates JS modules that use the ES module syntax. In some cases, it is beneficial to use es modules, such as in the case of module connections and tree jitters.

file-loader-options

In short, the new version of file loader uses esmodule syntax by default, which makes the way of referencing image files different from that of previous versions. By checking the release of its repository, we can find that this new feature was introduced in v4.3.0.

file-loader-versions

How to solve this problem? In the answer to the stackoverflow question just now, it is explained that there are two solutions:

When quoting pictures, add.defaultsuffix


<img src="require('assets/logo.png').default"/>

In the file loader configuration item of webpack, set esmodule to false


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

Comparing the two methods, it is obvious that you already know which method is better. So I modified the webpack configuration and then compiled it. It’s OK: wink.

build-success

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.