模块化js的尝试

最初想象

require.js

var es = {};
es.each = function(arr, fn) {
  var i = 0;
  while(arr.length !== i) {
    fn(i, arr[i]);
    i++;
  }
};
var count = 0;
var cache = {};
var module = {};
module.exports = null;
var arr = [];
var require = function(m, cb) {
  while(m[0]) {

    var js = document.createElement('script');
    js.src = m[0];
    js.id = m[0];
    js.charset = 'utf-8';
    document.querySelectorAll('head')[0].appendChild(js);

    count++;
    js.onload = function() {
      count--;
      if (count === 0) {
        es.each(arr, function(i, cb) {
          cb(require, module.exports, module);
          arr[i] = module.exports;
        });
        cb.apply(null, arr)
      }
    };
    m.shift();
  }
}

var define = function(cb) {
  var id = document.currentScript.id;
  cache[id] = {
    status: 'loading',
    callback: cb
  };
  arr.push(cb);
};

require(['a.js', 'b.js'], function(a, b) {
  console.log(a);// aaa
  console.log(b);// bbb
});

a.js

define(function(require, exports, module) {
  module.exports = 'aaa';
});

b.js

define(function(require, exports, module) {
  module.exports = 'bbb';
});
    原文作者:erichooooow
    原文地址: https://segmentfault.com/a/1190000004624601
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞