diff --git a/README.md b/README.md index 54986fa..0ce995e 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/index.js b/index.js index b47a19f..b1f8ae1 100644 --- a/index.js +++ b/index.js @@ -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); @@ -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(); + }); +} diff --git a/test/camelcase.js b/test/camelcase.js new file mode 100644 index 0000000..83be585 --- /dev/null +++ b/test/camelcase.js @@ -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.'); diff --git a/test/camelcase/a_main.js b/test/camelcase/a_main.js new file mode 100644 index 0000000..4b0ed58 --- /dev/null +++ b/test/camelcase/a_main.js @@ -0,0 +1 @@ +module.exports = 'a main'; diff --git a/test/camelcase/sub-dir/a-sub.js b/test/camelcase/sub-dir/a-sub.js new file mode 100644 index 0000000..8d25d5e --- /dev/null +++ b/test/camelcase/sub-dir/a-sub.js @@ -0,0 +1 @@ +module.exports = 'a sub';