Discover the technique for dynamically importing JavaScript modules
Have you ever encountered a scenario where you needed to load a JavaScript module dynamically?
Perhaps you are attempting to load a module from a folder, but you are unsure of the folder’s name because it is generated dynamically.
However, using code like this would not work:
import test from folder + '/test.js'
or
import test from `${folder}/test.js`
In such cases, you need to employ a technique called dynamic import. Follow these steps:
- Use the following syntax to dynamically import the module:
const test = await import(folder + '/test.js')
To delve deeper into this relatively new feature of JavaScript, I have authored an article titled JavaScript Dynamic Imports.