Dynamic Import in JavaScript

Published on 10 Nov, 2020

We have seen importing external JavaScript files using import statement.

import utils from "./utils.js";

Some of us also have seen how dynamic import is done with the help of Webpack. The same syntax is now part of official JavaScript. Now we do not have to load all dependencies on page load. We can load the modules dynamically.

if (condition) {
  const utils = await import("./utils.js");
  utils.myFunction();
}

import() function returns a promise. So we can resolve the Promise using await or .then() syntax.