Search code examples
webpackcommonjs

Why bother with dependencies list in CommonJS require.ensure()?


From the Webpack documentation (https://webpack.github.io/docs/api-in-modules.html#require-ensure):

Download additional dependencies on demand. The dependencies array lists modules that should be available. When they are, callback is called. If the callback is a function expression, dependencies in that source part are extracted and also loaded on demand. A single request is fired to the server, except if all modules are already available.

If dependencies in the source part are also extracted and loaded on demand, then why bother putting anything in the dependencies list?

I've seen examples like this that are very confusing (https://github.com/webpack/webpack/tree/master/examples/extra-async-chunk):

require.ensure(["./a"], function(require) {
    require("./b");
    require("./d");
});

"b" and "d" are not in the dependencies list, but will be loaded on demand just like "a". So what's the difference?


Solution

  • The example in the docs you linked to shows one way that behavior differs. When you specify a dependency, it explicitly creates a new chunk, puts the dependency in it, and adds any other dependencies referenced in the callback. When you don't specify a dependency, any dependencies in the callback are added to the 'current' (last?) chunk, a new chunk is not created.