Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A practice for handling common dependencies among multiple requirejs contexts?

I have started using requirejs contexts as a way to partition a large single page application that is composed of individual stand alone SPAs that have their own set of dependencies.

James Burke describes the problem that I am now encountering in this comment on github about multiple contexts and their common dependencies not being shared, https://github.com/aurajs/aura/pull/170#issuecomment-10973485

How do I share common dependencies between different requirejs contexts without causing duplicate requests for the same file?

like image 322
cs_brandt Avatar asked Feb 15 '13 19:02

cs_brandt


1 Answers

I encountered the same problem as you described. I wrote a plugin which takes care of sharing common dependencies between nested contexts.

Requirejs has a map which contains all contexts and it’s defined dependencies:

requirejs.s.contexts

{
  _: {
    defined: {
      commondep: {},
      main: undefined
    }
  }
  plugin: {
    defined: {
      commondep: {},
      plugin: {}
    }
  }
}

The _ context is the main context. We can use this context to determine all global module definitions. Shared dependencies can be determined by pre-loading the plugin scripts and comparing the dependencies to the global dependencies. Shared modules can be injected into the sandbox context:

function injectDependency(dependencyName, contextName) {
  var ctx = getContext(contextName);
  var dependencyInstance = require(dependencyName);

  ctx.defQueue.push([ dependencyName, [], function() { return dependencyInstance; }]);
}

function getContext(contextName) {
  return requirejs.s.contexts[contextName];
}

In this snippet we call require in a non-async way to get the global instance of the module. The module is injected in the sandbox by pushing it on the definition queue.

An implementation of this solution of the plugin loader can be downloaded from https://github.com/igsp/requireplug.

I posted a more detailed description of the mechanics of this solution on my blog: https://intergalacticspacepocket.wordpress.com/2014/08/07/nesting-requirejs-contexts-with-shared-dependencies/

like image 114
M. Hesselink Avatar answered Oct 04 '22 02:10

M. Hesselink