Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

webpack file-loader duplicates files

I'm using webpack and it's file-loader + html-loader to emit files into my output directory. It works almost as expected, because it also duplicates those files.

Here is a part of my webpack.config.js file:

module.exports = {
   module: {
      rules: [
         { test: /\.html$/, use: ["html-loader"] },
         {
            test: /\.(jpg|png)$/,
            use: {
               loader: "file-loader",
               options: {
                  name: "[name].[ext]",
                  outputPath: "img",
               },
            },
         },
      ],
   },
};

There is a small example of how my output directory looks like:

dist/
- img/
   - img1.png
   - img2.png
- ab0d12.png
- c3d612.png
- index.html
- bundle.js

The two images with hashed names are unwanted duplicates of those in img/ directory. As you can see in the example above, I'm not even setting the name to be hashed and I also cannot open the duplicate files in any way.

I'm using some plugins like HtmlWebpackPlugin or CleanWebpackPlugin, but I believe they are not causing the problem.

Versions:

  • webpack 5.28.0
  • file-loader 6.2.0
  • html-loader 2.1.2
like image 744
Daweed Avatar asked Apr 01 '21 15:04

Daweed


1 Answers

After a long searching I came across this SO question that seemed very similar to mine, however, the cause of the file duplication were different.

In version 5, webpack introduced Asset Modules as a replacement for raw-loader, url-loader and file-loader and which are now ran by default:

Asset Modules is a type of module that allows one to use asset files (fonts, icons, etc) without configuring additional loaders.

Every time webpack started bundeling my project, asset/resource and file-loader were running at the same time and resulted into duplication.

Eventually, all I had to do to fix my problem was to remove the file-loader from the webpack.config.js file and set a output.assetModuleFilename to my desire output directory.

like image 52
Daweed Avatar answered Nov 15 '22 12:11

Daweed