Skip to content

Instantly share code, notes, and snippets.

@dongyuwei
Last active February 23, 2016 12:35
Show Gist options
  • Save dongyuwei/0be0f41d7e57781a84f8 to your computer and use it in GitHub Desktop.
Save dongyuwei/0be0f41d7e57781a84f8 to your computer and use it in GitHub Desktop.
an tiny commonjs module loader
var fs = require('fs');
function require2(url){
var source = fs.readFileSync(url,'utf-8');
var code = new Function('exports, module', source);
var exports = {};
var module = {
exports: exports
};
code(exports, module);
return module.exports;
}
global.require2 = require2;
var foo = require2('./foo.js');
console.log(foo);
foo.hi();
@dongyuwei
Copy link
Author

cat foo.js

var bar = require2('./bar.js');
exports.hi = function(){
    console.log('hi, foo')

    bar();
}

cat bar.js

module.exports = function(){
    console.log('hi, baba')
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment