Understand Dynamic Importing in JavaScript

Understand Dynamic Importing in JavaScript

 

While working with JavaScript projects, as your project will grow, it will become very much a necessity to distribute your code into multiple files i.e. do some logical grouping by functionalities. When we are doing that, we are basically creating “modules”. A module is basically a JavaScript file that can contain classes, variables, or functions that are logically related.

In this series of two blog posts, I will be focusing on basic concepts of import/export from/in a module, some considerations, and dynamic importing.

In the first post, I have explained how the module works in JavaScript. If you have not read the post yet, I would request you to read the post and understand the basic concept first. You can read the post here and watch the video here. 

Note – I am sharing all my JavaScript Developer Certification study notes here. Please provide your feedback if you see anything wrong or missing. Appreciate.

In the second post, I will be discussing –

  • Why do we need dynamic importing?
  • Syntax of dynamic importing
  • Examples


Why do we need dynamic importing?

JavaScript standard import is very much static i.e. standard import will always evaluate all the imported modules at the run time, which is not very efficient. Rather we should evaluate imported modules only when it is really needed. 

Loading modules statically is having a performance impact as it slows the loading of the code significantly and increases the program’s memory usage.

Due to mainly these reasons, it is highly recommended to go for dynamic importing and evaluating of the modules only when it is really needed.

Syntax of dynamic importing?

To dynamically import a module, we need to use import keyword as a function. When used as a function, this will return a promise. And since it returns a promise, it is possible to use async-wait instead of then-based callback style. Don’t worry, I will share examples later in this post to explain this. Below is the syntax of dynamic importing where I have used import as a function that returned a promise.

import(“/modules/MYMODULE.js”).then((module) => {
//Operation
});


Examples

Let’s say I have a module named “operations.js” where I have a basic add function and I am exporting that function.

// * File Name: operations.js
function add(num1, num2) {
return num1 + num2;
}

export { add };

Now I would like to create the HTML page with a button and while clicking the button only, I would like import this above module and do the add operation. Try to understand the difference, here I am not importing the module at the very first time, rather I would like to import only when the button is clicked i.e. dynamically importing the module.

Here is the HTML page

<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“UTF-8” />
<meta http-equiv=“X-UA-Compatible” content=“IE=edge” />
<meta name=“viewport” content=“width=device-width, initial-scale=1.0” />
<title>Document</title>
</head>
<body>
<h1>Working with Modules – Dynamic Importing</h1>
<script type=“module” src=“Modules/Modules-1.js”></script>
<button id=“myButton”>Click me</button>
</body>
</html>

Here is the dynamic import code 

const btn = document.getElementById(“myButton”);
btn.addEventListener(“click”, buttonClicked);

function buttonClicked() {
console.log(“Button Clicked”);
import(“./operations.js”).then((module) => {
let addResult = module.add(10, 15);
console.log(addResult);
});
}

Now when the button will be clicked, then only the module operations.js will be imported. This is dynamic importing. As I mentioned already, dynamic importing returns a promise, so here I have used then-based callback style to call the add function from the module.

The same dynamic importing can be written using async/await instead of the then-based callback style. If that is your preferred style, the above code will look something like this –

const btn = document.getElementById(“myButton”);
btn.addEventListener(“click”, async () => {
const module = await import(“./operations.js”);
let addResult = module.add(10, 15);
console.log(addResult);
});

Video



I hope these two posts will help you to understand how “Import/Export Modules work in JavaScript”. 

Understand Modules in JavaScript

Understand Modules in JavaScript

 

While working with JavaScript projects, as your project will grow, it will become very much a necessity to distribute your code into multiple files i.e. do some logical grouping by functionalities. When we are doing that, we are basically creating “modules”. A module is basically a JavaScript file that can contain classes, variables, or functions that are logically related.

In this series of two blog posts, I will be focusing on basic concepts of import/export from/in a module, some considerations, and dynamic importing.

Note – I am sharing all my JavaScript Developer Certification study notes here. Please provide your feedback if you see anything wrong or missing. Appreciate.

In the first post, I will be discussing –

  • How to export variables, functions, and classes in a module
  • How to import variables, functions, and classes from a module
  • Important considerations while importing or exporting JavaScript module

In the second post, I will be discussing –

  • Why do we need dynamic importing?
  • Examples

How to export variables, functions, and classes in a module

Items from a module can be exported by using the export statement. Using export statement, it is possible to export functions, variables, classes. There are normally two types of exports available.
  • Named Export – Here all the features will be referred to by its name that is being used while exporting.
  • Default Export – It can be achieved using export default syntax. There can only be one default export per module.


Named Export

Below is the content of operations.js file where I am exporting two functions (add and subtract) and one variable (NAME).

// File Name: operations.js
function add(num1, num2) {
return num1 + num2;
}

function subtract(num1, num2) {
return num1 – num2;
}

const NAME = “SUDIPTA DEB”;

export { add, subtract, NAME };

The last line where I am using the export keyword is doing the job here i.e. exporting two functions and one variable.

Default Export

Below is the content of math.js file where I am doing default export of function which is doing a bunch of basic mathematical operations.
// File Name: math.js
export default function operation(type, num1, num2) {
switch (type) {
case “add”:
return num1 + num2;
case “minus”:
return num1 – num2;
case “multiply”:
return num1 * num2;
case “divide”:
return num1 / num2;
default:
return “Error”;
}
}
Using export default is doing the job here. You need to keep in mind one thing that in a module, there can be only one default import.

How to import variables, functions, and classes from a module

Items from a module can be imported by using the import statement. Using import statement, it is possible to import functions, variables, classes. I will be using the above modules and import them.
In the below example, I will import variable and functions from operations.js module. After import, I will call the functions and print the result in the console.
//Importing functions and variables from the module operations.js
import { add, subtract, NAME } from “./operations.js”;

let addResult = add(10, 15);
let subsctractResult = subtract(100, 15);
console.log(addResult); //This will print 25
console.log(subsctractResult); //This will print 85
console.log(NAME); //This will print SUDIPTA DEB
 
In the next example, I will import everything from operations.js module. After import, I will call the functions and print the result in the console. While important everything using *, we need to provide a name that will be used while referring to the items from the module. For example, in the below example, I will import everything and give it a name myOperation. Then I will use myOperation to call functions and variable.
//Importing functions and variables from the module operations.js
import * as myOperation from “./operations.js”;

let addResult = myOperation.add(10, 15);
let subsctractResult = myOperation.subtract(100, 15);
console.log(addResult); //This will print 25
console.log(subsctractResult); //This will print 85
console.log(myOperation.NAME); //This will print SUDIPTA DEB
What about importing items from the module and give them a new name? Yes, that is also possible. In the next example, I will import items from operations.js and give them a new name, which I will use later to refer them.
//Importing functions and variables from the module operations.js
import {
add as myAdd,
subtract as mySubtract,
NAME as myNAME,
} from “./operations.js”;

let addResult = myAdd(10, 15);
let subsctractResult = mySubtract(100, 15);
console.log(addResult); //This will print 25
console.log(subsctractResult); //This will print 85
console.log(myNAME); //This will print SUDIPTA DEB
In the next example, I will show you how you can import default exports. For this one, I will import the default export from math.js.

//Importing default export from the module math.js
import doMyMath from “./math.js”;

console.log(doMyMath(“add”, 10, 12)); //This will print 22
console.log(doMyMath(“minus”, 100, 12)); //This will print 88
console.log(doMyMath(“multiply”, 5, 2)); //This will print 10
console.log(doMyMath(“divide”, 500, 100)); //This will print 5
There is another way of doing the import, which is Dynamic Import. I will cover Dynamic Import in a separate future post.

Important considerations while importing or exporting JavaScript module

Below are the things you should know while doing the import or export in JavaScript.
  • The value of imported items are read-only which means they cannot be changed.
  • Module in JavaScript supports live-binding. That means if the value of property changes in the main module, it will be reflected in all the modules where it is imported.
  • Modules in JavaScript are always hoisted to the beginning of the current scope, which means it doesn’t matter where you write your import statement, it will always be hoisted at the beginning of the file

Video


Further reading

I hope this post will help you to understand modules in JavaScript. In my next post, I will be explaining Dynamic Importing. Till then enjoy learning.