Any Way to Reverse the Order of Require.Context?

In my particular use case, I have a folder structure like this:

  • angular
    • directives
      • date-range
        • index.js
      • module.js
  • module.js

And id like to simply do

require.context('./angular');

Right now it seems to include files in the bundle in child first order. So my directives are getting put in the file before the module definitions. Essentially Id like files higher up in the hierarchy to appear before files deeper in the hierarchy.

Is there anyway to do this with require.context?

Author: Fantashit

1 thought on “Any Way to Reverse the Order of Require.Context?

  1. I don’t think the order in which they are included in the bundle should really make a difference, should it? I’m guessing you’re concerned about the order in which they are executed if you have implicit dependencies like

    // a.js
    window.ModuleA = ...;
    
    // b.js
    window.ModuleB = /* using window.ModuleA */;

    In that case, I think you can achieve it like this:

    var context = require.context('./angular');
    var modules = context.keys();
    
    // sort them
    var sortedModules = modules.slice().sort(function(a, b) {
      // by directory depth
      var diff = a.match(/\//g).length - b.match(/\//g).length;
      if ( diff !== 0) return diff;
    
      // if depth is the same, sort alphabetically to make it stable
      return a < b ? -1 : (a > b ? 1 : 0);
    });
    
    // execute them
    sortedModules.forEach(function(key) {
      context(key);
    });

Comments are closed.