Skip to content

Instantly share code, notes, and snippets.

@ruanyf
Created May 20, 2015 08:36
Show Gist options
  • Save ruanyf/2b7723f8e9e4b0d28c16 to your computer and use it in GitHub Desktop.
Save ruanyf/2b7723f8e9e4b0d28c16 to your computer and use it in GitHub Desktop.
require() in browser
function require(p){
var path = require.resolve(p)
, 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
, reg = path + '.js'
, 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(p){
if ('.' != p.charAt(0)) return require(p);
var path = parent.split('/')
, 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('/'));
};
};
// 用法
// require.register("browser/debug.js", function(module, exports, require){
// module.exports = function(type){
// return function(){
// }
// };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment