This content originally appeared on DEV Community and was authored by Madushan Perera
You can find the original post on my blog. Thank you for visiting. ?
Why we need ‘import’ in JavaScript?
The static import is very useful when we want to use read only live bindings which are exporting by other modules in your program. In this way the idea is to manage our code by separating them as we want. This can be functionality, features or component wise. But the entire code is working as a one code block after connecting them by importing.
Below code block shows how we can import modules in a static way.
import defaultExport from "module-name";
import * as name from "module-name";
import { export1 } from "module-name";
import { export1 as alias1 } from "module-name";
import { export1 , export2 } from "module-name";
import { foo , bar } from "module-name/path/to/specific/un-exported/file";
import { export1 , export2 as alias2 , [...] } from "module-name";
import defaultExport, { export1 [ , [...] ] } from "module-name";
import defaultExport, * as name from "module-name";
import "module-name";
In this way it’s easier to understand the code to some and very helpful for debugging.
The import statement cannot be used in the embedded scripts unless the script has a type=’ module.’
Also, we can import modules as a dynamic import.
What’s dynamic import in JavaScript?
Most of the time developers are used to use the standard static import. This will always import the modules at the loading time. No matter what if we use that imported module or not JavaScript always loads the static modules in loading time.
What if we want to import modules conditionally or on demand? This is the place where you need to implement dynamic import in JavaScript.
To use dynamic import call the ‘import()’ as a function as pass the module path as an argument. Then you can use JavaScript promise or await to get the rest of the work done.
import("/modules/my-module.js").then((module) => {
// Do something with the module.
console.log("module-->", module);
});
let module = await import("/modules/my-module.js");
When to use dynamic import?
- When importing statically significantly slows the loading of your code.
- When importing statically significantly increases your program's memory usage.
- When the module you are importing does not exist at load time
- When the module being imported has side effects, and you do not want those side effects unless some condition is true.
- When the import specifier string needs to be constructed dynamically.
Thank you for reading and Happy Coding ?
This content originally appeared on DEV Community and was authored by Madushan Perera
Madushan Perera | Sciencx (2021-08-02T07:44:43+00:00) What is Dynamic Module Import ?. Retrieved from https://www.scien.cx/2021/08/02/what-is-dynamic-module-import/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.