Javascript - Dynamic Import (Module, Json)

About

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

The import() function-like form takes the module name as an argument and returns a Promise which always resolves to the namespace object of the module.

Example

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('https://cdn.jsdelivr.net/npm/[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 5) 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





Discover More
How to load a script dynamically with Javascript?

This page shows you how you can load a script dynamically with Javascript to load and use it when needed. In short, if you add: a script via an DOM element, it will be executed (via append or insertAdjacentElement)...
Javascript - Module Loader (Script Loader)

A loader searches and loads module and script into the javascript engine (environment). From the main script, they will: create a dependency graph from the require and import statement find them...
Javascript Module - Import (Es Module)

This page is the import statement defined in the es module specification The ES6 import is: a function for dynamic import (performed at runtime time) or a statement for static import (performed...
React - Lazy

The lazy function implements lazy loading. (ie it will let you defer loading component’s code until it is rendered/executed for the first time) It's part of code splitting meaning that the build step...
Code Splitting

Code splitting is an operation performed by a bundler that splits code into chunks. You can then load only what is needed for a page to render. It's also known as route-chunking (where route refers to...
What is RequireJs: the browser module loader ?

RequireJs is a browser module loader that implements the AMD specification . It may load also other modules (UMD, CommonJs) In this example, we will load the bowser...



Share this page:
Follow us:
Task Runner