Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MrRaindrop/abe430e6b5d859d17f6b to your computer and use it in GitHub Desktop.
Save MrRaindrop/abe430e6b5d859d17f6b to your computer and use it in GitHub Desktop.
js: simple implementation of browserifyjs
// author ranyifeng
// link: http://www.ruanyifeng.com/blog/2015/05/commonjs-in-browser.html
//
// Usage
//
// require.register("browser/debug.js", function(module, exports, require){
// // Module code goes here
// });
//
// var debug = require("browser/debug.js");
function require(p){
var path = require.resolve(p);
var mod = require.modules[path];
if (!mod) throw new Error('failed to require "' + p + '"');
if (!mod.exports) {
mod.exports = {};
mod.call(mod.exports, mod, mod.exports, require.relative(path));
}
return mod.exports;
}
require.modules = {};
require.resolve = function (path){
var orig = path; // "browser/debug.js"
var reg = path + '.js';
var index = path + '/index.js';
return require.modules[reg] && reg
|| require.modules[index] && index
|| orig;
};
require.register = function (path, fn){
require.modules[path] = fn;
};
require.relative = function (parent) {
return function({}}){
if ('.' != p.charAt(0)) return require(p);
var path = parent.split('/');
var segs = p.split('/');
path.pop();
for (var i = 0; i < segs.length; i++) {
var seg = segs[i];
if ('..' == seg) path.pop();
else if ('.' != seg) path.push(seg);
}
return require(path.join('/'));
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment