Search code examples
javascriptnode.jswebpackcommonjs

Pass Query Parameters to Loader via Webpack Require Context


I am using webpack's require.context to require a directory of thumbnail images. Furthermore in my webpack config file I am implementing a responsive-loader to build various resolutions of each image.

I would like to manually pass a query parameter to the responsive-loader to build only 128 and 256 width images when I require the thumbnail directory.

How can I pass a query parameter through webpack's require.context method?

Here is my code so far...

thumbnailContext.keys().forEach(thumbnailPath => {
    thumbnailContext(`${thumbnailPath}?sizes[]=128,sizes[]=256`)
})

That code returns this error.

Uncaught Error: Cannot find module './First Post/thumbnail.png?sizes[]=128,sizes[]=256'
    at webpackContextResolve (webpack:///./src/posts_sync_thumbnail\.(:8080/png%7Cjpeg%7Cjpg)?:12:11)

Solution

  • You have to pass the parameters as part of the first argument of require.context.

    Example:

    require.context('my-loader?sizes[]=128,sizes[]=256!./img', true, /\.png$/i);
    

    If you want to ignore all other loaders that might be configured, prefix it with !!

    require.context('!!my-loader!./img', true, /\.png$/i);