Skip to content
This repository was archived by the owner on Apr 6, 2021. It is now read-only.

Add require.js paths option to alias paths to external libraries. #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 25 additions & 14 deletions lib/amd-loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,24 @@ var Module = require("module");
var moduleStack = [];
var defaultCompile = module.constructor.prototype._compile;

module.constructor.prototype._compile = function(content, filename){
module.constructor.prototype._compile = function(content, filename){
moduleStack.push(this);
try {
try {
return defaultCompile.call(this, content, filename);
}
finally {
moduleStack.pop();
}
};

var paths = exports.paths = {};

global.define = function (id, injects, factory) {

// infere the module
var currentModule = moduleStack[moduleStack.length-1];
var module = currentModule || require.main;

// parse arguments
if (!factory) {
// two or less arguments
Expand All @@ -36,7 +38,7 @@ global.define = function (id, injects, factory) {
}
else{
// anonymous, deps included
injects = id;
injects = id;
}
}
else {
Expand All @@ -51,29 +53,38 @@ global.define = function (id, injects, factory) {
// async require
return callback.apply(this, relativeId.map(req))
}

var chunks = relativeId.split("!");
if (chunks.length >= 2) {
var prefix = chunks[0];
relativeId = chunks.slice(1).join("!");
}

var id = Module._resolveFilename(relativeId, module)[0];


for (var _path in paths) {
if (relativeId.slice(0, _path.length) == _path) {
var replace = paths[_path];
relativeId = replace + relativeId.slice(_path.length);
break;
}
}

var id = Module._resolveFilename(relativeId, module);

if (prefix && prefix.indexOf("text") !== -1) {
return fs.readFileSync(id);
} else
} else {
return require(id);
}
}.bind(this, module);

injects.unshift("require", "exports", "module");
injects.push("require", "exports", "module");

id = module.id;
if (typeof factory !== "function") {
// we can just provide a plain object
return module.exports = factory;
}

var returned = factory.apply(module.exports, injects.map(function (injection) {
switch (injection) {
// check for CommonJS injection variables
Expand All @@ -85,9 +96,9 @@ global.define = function (id, injects, factory) {
return req(injection);
}
}));

if (returned) {
// since AMD encapsulates a function/callback, it can allow the factory to return the exports.
module.exports = returned;
}
};
};