JavaScript dynamic import

Learn about upcoming new JavaScript features

I have never had the privilege to useDynamic importUntil recently, when I used them to enhance code splitting in Next.js applications, I still needed to do some research because they are related toStatic import.

Import ES modules staticallyDefault exportIt looks like this:

import moment from 'moment'

You can use object decomposition to get a named export:

import { format } from 'date-fns'

There are some restrictions on static imports:

  • They are limited to the top level of the file
  • They cannot be loaded conditionally (inif)
  • The name of the package cannot be determined at execution time

Dynamic import can accomplish all these things!

The syntax is slightly different.

They workIn the module.

You can use them like this:

const module = await import('module')

And use the default export, you must first call.default().

Examples of using moments:

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

On the other hand, the named import works as expected:

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

Can you use them today? Yes it is! ThisBrowser supportIt's already pretty good, there's one moreBabel plugin.

Download mine for freeJavaScript beginner's manual

More js tutorials: