What is `require.context`?

One of the main features of webpack's compiler is to recursively parse all the modules, starting from the entries, to build a graph of all the module dependencies by analyzing require(), require.context(), import and import() expressions.

The usual interpretation of "context" in webpack, and similarly in Node.js, is some directory that is used as a base for resolving paths to modules. For example, the current working directory is used as the default context for webpack to resolve the actual path to the index.js entry module; the context for the request require.resolve('../../../foo.js') is __dirname.

require.context is a special feature supported by webpack's compiler that allows you to get all matching modules starting from some base directory. The intention is to tell webpack at compile time to transform that expression into a dynamic list of all the possible matching module requests that it can resolve, in turn adding them as build dependencies and allowing you to require them at runtime.

In short, you would use require.context in the exact same situation when in Node.js at runtime you would use globs to dynamically build a list of module paths to require. The return value is a callable object that behaves like require, whose keys contain the necessary module request data that can be passed to it as an argument to require the module.

There are several ways you can use it, but I think the two most common use cases are to either automagically require some well-known kind of modules (e.g. you just add some.test.js test module and in some module you use require.context to dynamically discover all the tests, thus not having to document and remember to do it manually every time you add a new test module) or to load static assets in the repository to emit files to the build output (new webpack users coming from other build tools are usually surprised that their images, fonts, audio files and other assets do not appear in the output unless they are required from some module).

Tags:

Webpack