Javascript - Dynamic Import (Json)

About

dynamic import are import that are defined at runtime

Doc: Dynamic_Imports

Type

Json

If you want to load JSON file has object on node, you can just read it and parse it such as:

const dataObject = JSON.parse(fs.readFileSync('data/file.json'));

Example with:

  • The whole Json file
{
   "prop": {
     "id": 1,
     "name": "Nico"
   }
}
  • Return the whole object
file = 'data.json'
const data = await import(file).then(module => module.default);
  • Return only a sub-part
file = 'data'+'1.json'
const data = import(file).then( ( { prop: data} ) => data);
  • Typescript. If the import is really dynamic, typescript will complain and you need to assert the type
const examData = (
   (
      await import('../../data/exam'+id+'.json')
        .then(module => module.default)
   ) 
   as unknown as ExamSchema
);

Documentation / Reference


Powered by ComboStrap