Skip to content
azproduction edited this page Feb 13, 2013 · 4 revisions

Simple explanation

This 3 lines explains how the require works in most cases. Require can work with modules as functions/module, strings and objects w/o any plugins.

function require(name) {
    return cache[name] || modules[name] || window[name];
}

Complex explanation

  • if name in cache
    • return cache[name]
  • module become modules[name]
  • if module !undefined and module is @shortcut then name become string "shortcut"
    • module become modules[shortcut]
  • if module !undefined
    • module is lazy - a string && .startsWith('(function(')
      • module become Function('return ' + module)()
    • module is callable
      • module become module(require, exports, module) || module.exports
      • cache module under key name
      • return module
    • module is not callable
      • cache module under key name
      • return module
  • if module undefined then return globals[name] without cache
Clone this wiki locally