Created
July 14, 2015 07:06
-
-
Save MrRaindrop/abe430e6b5d859d17f6b to your computer and use it in GitHub Desktop.
js: simple implementation of browserifyjs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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