Javascript - Dynamic Import (Es module, Json)


dynamic import 1) 2) 3) is when the import statement is used as a function in order to execute it at runtime.


How to import an ES module

The import function:

  • fetches and executes an es module
  • returns a promise that resolves into a module object that contains all its exports.
import('[email protected]/dist/moment.js').then( ({ default: moment}) => {
    const now = moment().format();
    console.log(`The actual time is "${now}"`);

The import above expect the module to export a property named 'default'. ie at the end of the file, you could see something like that

export { Moment as default };

If this is not the case in your module, you may get this error:

The requested module 'xxxx' does not provide an export named 'default'

How to import Json data

JSON module 4) can also be imported dynamically.

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