mpen
mpen

Reputation: 282905

How does webpack's require.ensure work?

From the docs, you can do this:

require.ensure(["module-a", "module-b"], function(require) {
    var a = require("module-a");
    // ...
});

require.ensure does not evaluate the modules until you require() them. Later, they give another example,

require.ensure([], function(require) {
  let contacts = require('./contacts')
});

Where the ensure array is empty.

So my questions are:

  1. Do I have to specify my modules twice? Once as the first argument to require.ensure and again inside the callback? Are there differences between specifying or omitting that first arg?

  2. The callback gives me back a new require function but we already have a global one. Is there a difference between the local one and global one? Can webpack even differentiate them, since it has to do this statically?

Upvotes: 6

Views: 1462

Answers (1)

agoldis
agoldis

Reputation: 1067

Webpack now supports import(), which is more convenient to use. require.ensure still supported, so back to your questions:

  1. You don't have to specify modules twice. Webpack statically parses the source code and adds all modules mentioned in the first argument array and all required within callback function body modules to a distinct chunk

  2. Actually the function passed to callback is not used and you should always use global require. This is quirky behavior that I have noted at the official webpack documentation.

Upvotes: 1

Related Questions