Skip to content

Instantly share code, notes, and snippets.

@polyakovin
Last active June 8, 2020 19:25
Show Gist options
  • Save polyakovin/3c4751807a9ffb1281d37b1bac0a77a6 to your computer and use it in GitHub Desktop.
Save polyakovin/3c4751807a9ffb1281d37b1bac0a77a6 to your computer and use it in GitHub Desktop.
This script generates js code for importing all json files from specific folder.
const fs = require('fs');
const getImportsFromFiles = (files, templateFunction) => files
.filter(file => file.match(/\.json/))
.map(file => file.split('.json')[0])
.map(templateFunction)
.join('\n');
const replaceForbiddenSymbols = file => file
.replace(/\./g, '')
.replace(/\-/g, '_');
const fileToImport = file => `import * as ${replaceForbiddenSymbols(file)} from './${file}.json';`;
const fileToObjectProperty = file => ` '${file}': ${replaceForbiddenSymbols(file)},`;
const generateFileImportingJsons = files => `${getImportsFromFiles(files, fileToImport)}
export default {
${getImportsFromFiles(files, fileToObjectProperty)}
};
`;
fs.readdir(__dirname + '/path/to/folder/with/jsons', (err, files) => {
console.log(generateFileImportingJsons(files));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment