Amd 模块加载器简单实现

var registry = {}
var seen = {}

function missingModule(name, referrerName) {
  if (referrerName) {
    throw new Error(
      'Could not find module ' + name + ' required by: ' + referrerName
    )
  } else {
    throw new Error('Could not find module ' + name)
  }
}

function internalRequire(_name, referrerName) {
  var name = _name
  var mod = registry[name]

  if (!mod) {
    name = name + '/index'
    mod = registry[name]
  }

  var exports = seen[name]

  if (exports !== undefined) {
    return exports
  }

  exports = seen[name] = {}

  if (!mod) {
    missingModule(_name, referrerName)
  }

  var deps = mod.deps
  var callback = mod.callback
  var reified = new Array(deps.length)

  for (var i = 0; i < deps.length; i++) {
    if (deps[i] === 'require') {
      reified[i] = requireModule
    } else {
      reified[i] = internalRequire(deps[i], name).exports
    }
  }
  reified.unshift(exports)
  callback.apply(this, reified)

  return exports
}

define = function(name, deps, callback) {
  var value = {}
  if (arguments.length === 2) {
    if (typeof deps === 'function') {
      callback = deps
      deps = []
    }
  }

  value.deps = deps
  value.callback = callback

  registry[name] = value
}

requireModule = function(name) {
  return internalRequire(name, null)
}

define('a', function(module) {
  module.exports = 1
})
define('b', function(module) {
  module.exports = 2
})
define('container', ['a', 'b'], function(module, a, b) {
  console.log(a + b)
})

internalRequire('container')

from emberjs

你可能感兴趣的:(Amd 模块加载器简单实现)