Skip to content

Instantly share code, notes, and snippets.

@dmurawsky
Created August 25, 2017 02:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmurawsky/4a0d861eb5a1277c5635ef60616decb5 to your computer and use it in GitHub Desktop.
Save dmurawsky/4a0d861eb5a1277c5635ef60616decb5 to your computer and use it in GitHub Desktop.
Node.js script to populate an index.js file with all files in a directory and export as an object using ES6 export syntax.
const fs = require('fs');
const Populate_Index_ES6 = () => {
const path = __dirname + '/src/dir';
// Read directory
fs.readdir(path + '/components', (err, items) => {
let output = '';
// Add import statements for each file
for (let i=0; i<items.length; i++) {
let file = items[i].substring(0, items[i].length-3);
output = output + `import ${file} from './components/${file}'\n`;
}
output = output + '\n';
output = output + 'export default {\n';
// Add files to export object
for (let i=0; i<items.length; i++) {
let file = items[i].substring(0, items[i].length-3);
output = output + ` ${file},\n`;
}
output = output + '}';
// Write to index.js
fs.writeFile(path + '/index.js', output, err => {
if (err) throw err;
console.log('\nGenerated index.js file in ' + path); // eslint-disable-line
});
});
};
module.exports = Populate_Index_ES6;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment