Skip to content

Latest commit

 

History

History
56 lines (36 loc) · 2.48 KB

README.md

File metadata and controls

56 lines (36 loc) · 2.48 KB

Context Module require.context()

The concept of context in webpack (and nodejs) refer to some directory that is used as a base for resolving paths to modules.

Webpack analyze require(), import, import() and require.context at compile time to build a dependency graph of all modules.

The require.context() function is a special webpack feature that allow you to get all module paths (files) from a base directory. One common use case is to dynamically import static assets.

In other words, require.context() is a form of code splitting .

How it works

const r = require.context(
  // Directory path must be literal
  "./path/to/directory",
  // Recursive (use subdirectories)
  false,
  // Match files with regexp
  /\.jpg$/
);

const imagesPaths = r.keys();
// -> ["./image1.jpg", "./image2.jpg"]

const parsed_image1 = r(imagesPaths[0]);
// -> 73728f89fad1b84b9a3d.jpg

Explain this example

In this example require.context is used to get all images inside a directory. When you require load-images.js inside html, html-webpack-plugin run it and images become part of dependencies graph, load-images.js is not added in output build, it's just parsed by webpack at compilation time.

How to debug webpack

To see the logs inside load-images.js you have to debug webpack using nodejs debug tool.

Notes

You can't pass variable as argument inside require.context() because it must be statically analyzable (webpack#4772, so#42118921).

Even if you comment out require statements inside html:

<!-- <img src="<%= require('./load-images.js')[0] %>"> -->
<!-- <img src="<%= require('./load-images.js')[1] %>"> -->

Webpack will run load-images.js anyway (if you have errors inside load-images.js they will show up) but do not output images.

To debug load-images.js see how to debug webpack.

Further reading