AI Workshop: learn to build apps with AI →
Advanced JavaScript: Dynamic imports

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


A static import of an ES Module default export looks like this:

import moment from 'moment'

You can use object destructuring to get a named export:

import { format } from 'date-fns'

Static imports have some limits:

  • they are limited to the top level of the file
  • they can’t be loaded conditionally (inside an if)
  • the name of the package can’t be determined at execution time

Dynamic imports can do all those things!

The syntax is a little bit different.

And they work within modules.

You use them like this:

const module = await import('module')

and to use the default export, you must access the .default property.

Example using moment:

const moment = (await import('moment')).default

Named imports on the other hand work as expected:

const { format } = await import('date-fns')

You can also load something from a folder when you don’t know the name of the folder, generating it dynamically:

const test = await import(folder + '/test.js')

or using template literals:

const test = await import(`${folder}/test.js`)

Browser support is already pretty good, and there’s also a Babel plugin if you need to support older browsers.

Lessons in this unit:

0: Introduction
1: Generators
2: Symbols
3: Proxy objects
4: Memoization
5: Functional programming
6: ▶︎ Dynamic imports