Static Import in Ecmascript

Before ES10, Static imports are supported, Dynamic imports are not supported. There is no import support in before ES6, ES6 introduced import and export features. Below is an example for static import in javascript.

mymodule is created and exported using export keyword

// mymodule.js
export function getMessage() {
  return "Hello world";
}

import mymodule using import keyword

// main.mjs
import { getMessage } from './mymodule.js';
let message = getMessage();  // output  "Hello world";

Important points that can be achieved with static import

  • Static imports can be declared at top of the file only.
  • Not allowed to import where ever required like in event handlers or conditional expression ie if statements
  • Imports the functionality at compile time only
  • Advantages with static is bundling library and tree shaking
  • It has module specifier(./mymodule.js) is fixed and will not change at runtime

Disadvantages with static imports

  • Import the modules wherever required instead of fixed import.
  • change Module specifier at runtime is not possible
  • import modules in regular script files
  • assign the imports to variables

All the disadvantages of static imports are solved in ES10 Dynamic imports feature

Dynamic Import

It introduced new function syntax form import(moduleSpecificer) that returns retrieved module promise. It retrieves the module, its dependencies and initializes the modules.

Here is an syntax for dynamic import

import(moduleSpecifier)

The parameters are

  • accepts moduleSpecifier as input
  • returns promise of request module
const mymoduleSpecifier = './mymodule.js';
    import(mymoduleSpecifier)
        .then((module) => {
            module.getMessage();// outputs Hello world
    });

import() returns promises, so we can also replaces then with async and await feature

async and await dynamic import example As you see in the below example, import specifier assigned to variable using await in async block of code

  (async () => {
const mymoduleSpecifier = './mymodule.js';
    const module = await import(mymoduleSpecifier)
            module.getMessage();// outputs Hello world
  })();

Browser Support

This features Supports following browser versions.

  • Chrome 63+
  • Firefox 67+
  • Safari 11.1
  • Babel plugin

Babel plugin-syntax-dynamic-import To install this feature nodejs applications, Please add plugin-syntax-dynamic-import as devDependencies

npm install --save-dev @babel/plugin-syntax-dynamic-import

configure .babelrc file by adding plugins entry as follow

{
  "plugins": ["@babel/plugin-syntax-dynamic-import"]
}