Skip to content

Commit

Permalink
Merge pull request #13 from coderhaoxin/cam
Browse files Browse the repository at this point in the history
add support for camelcase alias
  • Loading branch information
aseemk committed Mar 24, 2015
2 parents e7499e8 + 9a25159 commit 4feb44b
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 0 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,10 @@ var dir = requireDir('./path/to/dir', {recurse: true});
(`node_modules` within subdirectories will be ignored.)
Default is false.

`camelcase`: Automatically add camelcase aliases for files with dash- and
underscore-separated names. E.g. `foo-bar.js` will be exposed under both the
original `'foo-bar'` name as well as a `'fooBarBaz'` alias. Default is false.

`duplicates`: By default, if multiple files share the same basename, only the
highest priority one is `require()`'d and returned. (Priority is determined by
the order of `require.extensions` keys, with directories taking precedence
Expand Down
18 changes: 18 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ module.exports = function requireDir(dir, opts) {
// default arguments:
dir = dir || '.';
opts = opts || {};
var camelcase = !!opts.camelcase;

// resolve the path to an absolute one:
dir = Path.resolve(parentDir, dir);
Expand Down Expand Up @@ -120,5 +121,22 @@ module.exports = function requireDir(dir, opts) {
}
}

if (opts.camelcase) {
for (var base in map) {
// protect against enumerable object prototype extensions:
if (!map.hasOwnProperty(base)) {
continue;
}

map[toCamelCase(base)] = map[base];
}
}

return map;
};

function toCamelCase(str) {
return str.replace(/[_-][a-z]/ig, function (s) {
return s.substring(1).toUpperCase();
});
}
20 changes: 20 additions & 0 deletions test/camelcase.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
var assert = require('assert');
var requireDir = require('..');

assert.deepEqual(requireDir('./camelcase', {
recurse: true,
camelcase: true
}), {
aMain: 'a main',
'a_main': 'a main',
subDir: {
aSub: 'a sub',
'a-sub': 'a sub'
},
'sub-dir': {
aSub: 'a sub',
'a-sub': 'a sub'
}
});

console.log('Camelcase tests passed.');
1 change: 1 addition & 0 deletions test/camelcase/a_main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = 'a main';
1 change: 1 addition & 0 deletions test/camelcase/sub-dir/a-sub.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = 'a sub';

0 comments on commit 4feb44b

Please sign in to comment.