[Javascript]How to Dynamically import modules

In this article, we will discuss how to dynamically import modules in JavaScript.




The method using “await”

This method can be used inside <script type=’module’></script> within an async function.

const { func1, func2 } = await import('./sampleModule.js')
func1()
func2()


It is also possible to receive the entire module.
Default functions can be called using the default method, not the function name.

const sampleModule = await import('./sampleModule.js')
sampleModule.default()
sampleModule.func1()
sampleModule.func2()





The method using “then”

You can also use the then method.

import('./sampleModule.js').then(({func1, func2}) => {
    func1()
    func2()
})


To receive the entire module, you write as follows.

import('./sampleModule.js').then((module) => {
    module.default()
    module.func1()
    module.func2()
})





You can use variables for the import path

In static imports, if you try to use a variable in the path, you will get an error and it’s not possible.
However, in dynamic imports, it is possible!

const path = './sampleModule.js'
const sampleModule = await import(path)

sampleModule.default()
sampleModule.func1()
sampleModule.func2()





You can also add timestamps.

You can also add timestamps to the import path!
This was a lifesaver when I was using a certain CMS with overly aggressive caching.

const sampleModule = await import(`./sampleModule.js?t=${Date.now()}`)
sampleModule.default()
sampleModule.func1()
sampleModule.func2()






That is all, it was about how to dynamically import modules in JavaScript.

Sponsored Link

You can subscribe by SNS

Sponcerd Link

Leave a Reply

*