Search code examples
javascriptimportdynamic-importastrojs

Does Astro have a way to do Next.js-style "Dynamic Imports"?


Next.js has a feature called Dynamic Imports, where you can wrap a import function call in a Next.js provided dynamic function and the file will be bundled, provided via server available directly to the front-end browser code. Does Astro provide anything like this feature?


Solution

  • Yes, "Dynamic Imports" are standard and supported in Astro js.

    You can use them for example in a client <script> tag of a .astro file like this

    <script>
        const card = await import('./Card')
        card.init_card(".card")
    </script>
    

    Reference Example

    To ensure that the import is really happening on demand and not on page load, this example intentionally defers loading with two seconds, which is possible to verify on a debug "Network" Panel https://github.com/MicroWebStacks/astro-examples#09_dynamic-imports