ECMAScript (aka ES2015, or ES) modules are a way to organize cohesive chunks of code in JavaScript.

ES modules system has 2 actors:

  1. The importing module — the one that uses import { func } from './myModule'
  2. The imported module — the one which exports export const func = () => {}.

The importing module uses import syntax to import a dependency:

// The importing module
import { concat } from './concatModule';

concat('a', 'b'); // => 'ab'

While the imported module exports its components using export syntax:

// The imported module exports components
export const concat = (paramA, paramB) => paramA + paramB;

import { concat } from './concatModule' way of using ES modules is static: meaning that the dependencies between modules are known at compile time.

While static importing works in most situations, sometimes you’d like to save the client’s bandwidth and load modules conditionally.

You can import modules dynamically if you use import as a function — import(pathToModule). Dynamic import is a JavaScript language feature starting ES2020.

Let’s see how dynamic import works, and when you might find it useful.

#javascript #es6 #programming #developer

How to Dynamically Import ECMAScript Modules
4.15 GEEK