Instantly share code, notes, and snippets.

Embed
What would you like to do?
Imports and webpack contexts

Imports and webpack contexts

This is an example to my article “How webpack’s ContextReplacementPlugin works”

Each time webpack encounters a dynamic import like this:

require('./locale/' + name + '.js')

it extracts from it three pieces of information:

  • directory in which to search for the files (./locale)
  • regular expression to test the files against (/^.*\.js)
  • and if webpack should look for the files in the subdirectories (always true by default).

Here’re some examples of dynamic imports and corresponding contexts.


require(path);

When you specify only a single variable, there isn’t enough information for webpack to create a context. You’ll see the following warning when doing a build:

WARNING in ./index.js
Critical dependency: the request of a dependency is an expression

require(path + '.js');

regular expression: ^.*\.js$, recursive: true


require(path + '/index.js');

regular expression: ^.*\/index\.js$, recursive: true


require('./existing-directory/' + path + '/index.js');

regular expression: ^.*\/index\.js$, directory: absolute path of ./existing-directory, recursive: true


require('./non-existing-directory/' + path + '/index.js');

You’ll see the following error when doing a build:

Module not found: Error: Can't resolve './non-existing-directory' in '<absolute-path>/index.js'

require(part1 + 'staticPart2' + part3 + '.js');

regular expression: ^.*\.js$, recursive: true (All the expressions in the middle of concatenation are not evaluated.)


require('./existing-directory/' + part1 + 'staticPart2' + part3 + '.js');

regular expression: ^.*\.js$, directory: absolute path of ./existing-directory, recursive: true (All the expressions in the middle of concatenation are not evaluated.)


require(flag ? 'staticPathA' : 'staticPathB');
require('staticPathA' + 'staticPathB');
require('staticPathA'.substr(0, 5));

These are simpler expressions that don’t require creating a context. See parser evaluation

Follow me on Twitter: @iamakulov

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment