Last active
March 16, 2018 09:48
-
-
Save EmilienD/4782841979af52da4ce4beced4bf0df6 to your computer and use it in GitHub Desktop.
generate an index.js file as a commonjs style module
This file contains hidden or 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
| // usage: `node index-dot-js-maker.js <target directory>` | |
| const Promise = require('bluebird'); | |
| const fs = Promise.promisifyAll(require('fs')); | |
| const path = require('path'); | |
| const _ = require('lodash'); | |
| const cwd = process.cwd(); | |
| const maindir = path.resolve(cwd, process.argv[process.argv.length - 1]); | |
| const indexFilenameMapper = filename => path.resolve(maindir, filename, 'index.js'); | |
| const fileExistsMapperAsync = filePath => fs.accessAsync(filePath, fs.constants.F_OK) | |
| .then(() => true) | |
| .catch(() => false); | |
| const isJs = filename => filename.match(/^.*\.js$/); | |
| const isSpec = filename => filename.match(/^.*\.spec\.js$/); | |
| const isIndex = filename => filename.match(/index\.js/); | |
| fs.readdirAsync(maindir) | |
| .then((filenames) => { | |
| const jsFiles = filenames | |
| .filter(filename => isJs(filename) && !isSpec(filename) && !isIndex(filename)) | |
| .map(filename => filename.replace('.js', '')); | |
| const folderPromises = filenames | |
| .filter(filename => !isJs(filename)) | |
| .map(filename => fileExistsMapperAsync(indexFilenameMapper(filename)) | |
| .then(exists => exists && filename) | |
| ); | |
| return Promise.filter(jsFiles.concat(folderPromises), val => val); // remove falsy values from "exists" check | |
| }) | |
| .then((filesToIndex) => { | |
| const orderedFiles = filesToIndex.sort(); | |
| const requireLines = orderedFiles | |
| .map(filename => `const ${_.camelCase(filename)} = require('./${filename}');`) | |
| .join('\n'); | |
| const exportsLines = orderedFiles | |
| .map(filename => ` ${_.camelCase(filename)},`) | |
| .join('\n'); | |
| const indexDotJsFile = | |
| `${requireLines} | |
| module.exports = { | |
| ${exportsLines} | |
| }; | |
| `; | |
| fs.createWriteStream(path.resolve(maindir, 'index.js')).end(indexDotJsFile); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment