Permalink
Browse files

Relative require support

  • Loading branch information...
sstephenson committed Feb 20, 2011
1 parent f6db7f6 commit bf47be97aa4ad9128a7ac751ab4cb6048bcaf705
View

Some generated files are not rendered by default. Learn more.

Oops, something went wrong.
View
@@ -34,21 +34,44 @@ exports.Package = class Package
result = """
(function(/*! Stitch !*/) {
if (!this.#{@identifier}) {
var modules = {}, cache = {}, require;
this.#{@identifier} = require = function(name) {
var module = cache[name], fn;
var modules = {}, cache = {}, require = function(name, root) {
var module = cache[name], fn, path = expand(root, name);
if (module) {
return module;
} else if ((fn = modules[name]) || (fn = modules[name + '/index'])) {
} else if ((fn = modules[path]) || (fn = modules[path = expand(path, './index')])) {
module = {id: name, exports: {}};
fn(module.exports, require, module);
fn(module.exports, function(name) {
return require(name, dirname(path));
}, module);
cache[name] = module.exports;
return module.exports;
} else {
throw 'module \\'' + name + '\\' not found';
}
}, expand = function(root, name) {
var results = [], parts, part;
if (/^\\.\\.?(\\/|$)/.test(name)) {
parts = [root, name].join('/').split('/');
} else {
parts = name.split('/');
}
for (var i = 0, length = parts.length; i < length; i++) {
part = parts[i];
if (part == '.' || part == '') {
} else if (part == '..') {
results.pop();
} else {
results.push(part);
}
}
return results.join('/');
}, dirname = function(path) {
return path.split('/').slice(0, -1).join('/');
};
require.define = function(bundle) {
this.#{@identifier} = function(name) {
return require(name, '.');
}
this.#{@identifier}.define = function(bundle) {
for (var key in bundle)
modules[key] = bundle[key];
};
@@ -0,0 +1,2 @@
exports.a = "a";
exports.b = require("./b");
@@ -0,0 +1 @@
module.exports = "b";
@@ -0,0 +1,4 @@
exports.a = require("./a");
exports.custom = require("../custom_exports");
exports.baz = require("../foo/bar/baz").baz;
exports.buz = require("../foo/bar/../buz").buz;
View
@@ -6,7 +6,7 @@ fixtureRoot = __dirname + "/fixtures"
fixtures = fixtureRoot + "/default"
altFixtures = fixtureRoot + "/alternate"
addlFixtures = fixtureRoot + "/additional"
fixtureCount = 8
fixtureCount = 11
defaultOptions =
identifier: "testRequire"
@@ -211,3 +211,18 @@ module.exports =
test.same "additional/foo/bar.js", @testRequire("foo/bar").filename
test.same "biz", @testRequire("foo/bar/baz").baz;
test.done()
"relative require": (test) ->
test.expect 6
defaultPackage.compile (err, sources) ->
test.ok !err
eval sources
relative = @testRequire("relative")
test.same "a", relative.a.a
test.same "b", relative.a.b
test.same "foo", relative.custom()
test.same "biz", relative.baz
test.same "BUZ", relative.buz
test.done()

0 comments on commit bf47be9

Please sign in to comment.