Created
March 2, 2017 08:15
-
-
Save mofax/3a8fc817bdf7708f433c6c765a8ec744 to your computer and use it in GitHub Desktop.
automatically require all files inside a directory via an index.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
let fs = require('fs'); | |
let path = require('path'); | |
function snakeToCamel(s) { | |
let strings = s.split('_').map((str, index) => { | |
if (index === 0) return str; | |
return str.replace(/(^| )(\w)/g, function (x) { | |
return x.toUpperCase(); | |
}); | |
}) | |
return strings.join(''); | |
} | |
function asVar(name) { | |
return snakeToCamel(name.replace('.js', '')); | |
} | |
function init() { | |
let container = {}; | |
let dir = path.dirname(__filename); | |
let files = fs.readdirSync(dir); | |
files = files.filter(file => file !== 'index.js' && file.endsWith('.js')); | |
for (let file of files) { | |
container[asVar(file)] = require(`./${file}`); | |
} | |
return container; | |
} | |
module.exports = init(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment