Import all json files placed inside folder instead of import every file and export in Create React App?

Viewed 2654

I have requirement to import all json file which are placed inside the folder.

My Current Implementation -

import TXT1 from "../Assets/TTCS1.json";
import TXT2 from "../Assets/TTCS2.json";

export { TXT1, TXT2 }

I feel above implementation is not a good practice. I want to import all files once without importing every file.

Can any one help me to give good suggestion on this?

Thanks in Advance.

1 Answers

Try using require.context:

const context = require.context('../Assets', true, /.json$/);
const all = {};
context.keys().forEach((key: any) => {
  const fileName = key.replace('./', '');
  const resource = require(`../Assets/${fileName}`);
  const namespace = fileName.replace('.json', '');
  all[namespace] = JSON.parse(JSON.stringify(resource));
 
});
console.log(all)
Related