Search code examples
javascriptimagewebpackwebpack-file-loader

Some images loaded through Webpack file-loader are not found


I am working on a project which is bundling a pre-loaded set of stock images with the webapp using Webpack. There are about 400 images, half of which are thumbnails. Instead of writing 400 require statements, I create a new context and load them iteratively.

webpack.config.js

entry: __dirname + '/src/main/webapp/app/main.js',

//...

// there are other loaders but this is the one in question
module: {
  loaders: [
    {
      test: /\.(png|jpg)$/,
      loader: "file-loader?name=img/[name].[ext]"
    }
  ]
}

main.js

var stockImageReq = require.context(
  './images/stock',
  true,
  /\.jpg$/igm
);

stockImageReq.keys().forEach(function( imageName ) {
  console.log(imageName);
  stockImageReq(imageName);
}

All of the stock images live within the /images/stock directory and are served to /img. The problem is that when webpack finishes bundling up the static assets, it only provides just over half of the images in the directory (the console.log within the loop only prints about 230 filenames). When visiting the images within browser, the ones not listed in the bundle are 404s. There are no errors thrown in the log, so it seems that require is finding all of the images in their proper place.

Does anyone know why some images load just fine, but others are not? All are jpgs, the largest in question is about 5MB, with most around 1MB (for a bundle around 300MB total), and there is nothing different about how they were created (all from the same designer)


Solution

  • Turns out that removing the regex modifiers (igm) solved this. I don't know if it's a limitation of require.context or not, but all 400 of the images are properly loading now.

    This is what I ended up with

    var stockImageReq = require.context(
      './images/stock',
      true,
      /^.*\.(png|jpe?g)$/
    );
    
    stockImageReq.keys().forEach(stockImageReq);