What is Dynamic Import in JavaScript?

What is Dynamic Import in JavaScript?

·

3 min read


Hello, guy's let's hunt what is dynamic import in JavaScript?


Dynamic Imports

  • The standard import syntax is static and will always result in all code in the imported module being evaluated at load time. In situations where you wish to load module conditionally or on-demand, you can use a dynamic import instead.

  • To dynamically import a module, the import keyword may be called as a function. When used this way, it returns a promise.

    import('/modules/my=moudle.js')
     .then((module) => {
        // Do something with the module 😉
    });
    
  • This form also supports the await keyword.

    let module = await import('/modules/my-module.js');
    

Note: Dynamic imports ES 2020 (ES 11) feature is fully supported by Chrome 63+, Firefox 67+, Safari 11.1+ and NodeJS 13.2.0 (By importing either commonJS or ES module files)


When to use Dynamic Imports?

  • Loading code in demand

    button.addEventListener('click', event => {
        import('dialogBox.js')
        .then(dialogBox => {
            dialogBox.open(); 
        })
        .catch(error => {/* Error Handling */})
    });
    
  • Conditional loading of modules

    if (isLegacyPlatform()) {
        import(...)
        .then(...); 
    }
    
  • Computed module specifiers

    import(`messages_${getLocale()}.js`)
    .then(...);
    

Why to use Dynamic Imports?

  • When importing statically, it significantly slows the loading of your code and there is a low likelihood that you will need the code your are importing, or you will not need it until a later time.
  • When importing statically, it significantly increases your program's memory usage and there is a low likelihood that you will need the code you are importing.
  • When the module you are importing does not exist at load time.
  • When the import specifier string needs to be constructed dynamically. (Static import only supports static specifiers)
  • When the module being imported has side effects, and you do not want those side effects unless some condition is true. (It is recommended not to have any side effects in a module, but you sometimes cannot control this in your module dependencies)

☕Thanks For Reading | Happy Scripting 👊

Did you find this article valuable?

Support Rahul by becoming a sponsor. Any amount is appreciated!