Dynamic imports

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

Dynamic imports

Dynamic Imports let you import JavaScript Modules anytime you wish to (instead of importing it right at the top).

Dynamic imports uses Promises. It has the following syntax.

import('./path-to-module.js')
  .then(module => { /* do something with module */ })
  .catch(error => { /* handle error */ })

The module object here contains all named exports and default exports.

// library.js
export const one = 'named one'
export const two = 'named two'
export default 'default export'
// main.js
import('./library.js')
  .then(module => { console.log(module) })
Logs module from dynamic import

You can get named exports by using their name. You can also get the default export with the default property.

// main.js
import('./library.js')
  .then(module => {
     console.log(module.one)
     console.log(module.two)
     console.log(module.default)
  })
Logs each exported variable inside main.js.

You can destructure named exports.

// main.js
import('./library.js')
  .then(module => {
     const { one, two } = module
     console.log(one)
     console.log(two)
  })
Destructure named exports.

But you cannot destructure default normally. This is because default is a reserved keyword. You need to assign the default export to another variable name.

// main.js
import('./library.js')
  .then(module => {
    const { default: library } = module
    console.log(library)
  })
Destructured default export.