4

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.

Jaypal Thakur
  • 41
  • 1
  • 2
  • Does this answer your question? [Is it possible to import modules from all files in a directory, using a wildcard?](https://stackoverflow.com/questions/29722270/is-it-possible-to-import-modules-from-all-files-in-a-directory-using-a-wildcard) – demkovych Jun 29 '20 at 12:56
  • If you need that for JSON files only: [check this answer](https://stackoverflow.com/questions/61410909/dynamically-loading-json-files-with-fetch-after-component-mounts-in-react/61411455#61411455) – CevaComic Jun 29 '20 at 13:00
  • @demkovych I tried your solution using wildcard but it does not import JSON files. – Jaypal Thakur Jun 29 '20 at 14:04
  • are u using create react app? – demkovych Jun 29 '20 at 14:06
  • as a variant you can store your JSON file with the .js extension and make sure that your JSON should be in same directory. – demkovych Jun 29 '20 at 14:06
  • @demkovych Yes am using Create React App – Jaypal Thakur Jun 29 '20 at 14:53

1 Answers1

5

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)
Tudor Morar
  • 3,720
  • 2
  • 27
  • 25