Combining require.ensure with a dynamic require

I’ve finally found one possible solution to configuring how chunks should be created for my app, it looks something like this:

resolvers.index = function(name, cb) {
  require.ensure([
    "app/modules/foo/routes/a",
    "app/modules/foo/routes/b",
    "app/modules/foo/routes/c"
  ], function (require) {
    cb(require("app/modules/foo/routes/" + name));
  }, "index");
};

resolvers.review = function(name, cb) {
  require.ensure([
    "app/modules/foo/routes/d",
    "app/modules/foo/routes/e"
  ], function (require) {
    cb(require("app/modules/foo/routes/" + name));
  }, "review");
};

Here, the router will call resolvers.index("a"), resolvers.index("b") or resolvers.review("e"), etc. whenever it wants to load that page. require.ensure makes sure a named chunk is created for each group of routes. This is exactly what I want.

However, in the callback I need to require a specific route by name. Unfortunately require("app/modules/foo/routes/" + name) creates a dynamic context and forces everything into that chunk. So instead of having chunks “index” and “review”, I get a chunk “index” with all of the routes in it. Any suggestions?

Author: Fantashit

1 thought on “Combining require.ensure with a dynamic require

  1. Fine.

    Just a note: You could to it with your orignal structure:

    resolvers.index = function(name, cb) {
      require.ensure([], function() {
        cb(require.context("app/modules/foo/routes", false, /^\.\/(a|b|c)$/)("./" + name));
      });
    }

    But I would also recommend your approach with different folders. (require.context is non-standard)

Comments are closed.