Skip to content

Instantly share code, notes, and snippets.

@hayeah
Created October 29, 2016 02:35
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 hayeah/b3e9ba11440510d76aa3d9774944ea67 to your computer and use it in GitHub Desktop.
Save hayeah/b3e9ba11440510d76aa3d9774944ea67 to your computer and use it in GitHub Desktop.
wx app require implementation
var dir = function (e) {
var t = e.match(/(.*)\/([^\/]+)?$/);
// 默认相对于当前目录
return t && t[1] ? t[1] : "./"
},
// the inner require path is relative to the base directory of the requiring file.
_require = function (path) {
var baseDir = dir(path);
return function (e) {
if ("string" != typeof e) throw new Error("require args must be a string");
for (var normalizedParts = [], parts = (baseDir + "/" + e).split("/"), i = 0, len = parts.length; i < len; ++i) {
var part = parts[i];
if ("" != part && "." != part)
if (".." == part) {
if (0 == normalizedParts.length) throw new Error("can't find module : " + e);
normalizedParts.pop()
} else i + 1 < len && ".." == parts[i + 1] ? i++ : normalizedParts.push(part)
}
try {
var noramlizedPath = normalizedParts.join("/");
return /\.js$/.test(noramlizedPath) || (noramlizedPath += ".js"), require(noramlizedPath)
} catch (e) {
throw e
}
}
};
require = function (path) {
if ("string" != typeof path) throw new Error("require args must be a string");
// all module paths are relative to project root
var i = modules[path];
if (!i) throw new Error('module "' + path + '" is not defined');
if (i.status === e) {
var factory = i.factory,
module = {
exports: {}
},
undef = void 0;
factory && (undef = factory(_require(path), module, module.exports)), i.exports = module.exports || undef, i.status = t
}
return i.exports
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment