My Development Notes

Programming Made Easier


Basics of JavaScript Modules using Import and Export keywords

A Brief Explanation

Modules are actually certain independent pieces of code syntax which can be used and reused in certain other places, when required.

The reason we use modules is because they help to segregate code segments into different files, folders or pages. You don’t really need to write one single long page of JavaScript code. You just need to link them to each other when required.

To make it easy for you to understand, let’s say there’s a group of 5 carpenters. All of them need a certain type of big hammer and a small hammer to do their job. However, they have say, only 3 hammers (2 big and 1 small). So, once in a while they can borrow each other’s hammers as and when it’s needed. They can use them, and pass them on to someone else. That’s how JS modules also work – call, use and reuse.

Since it’s like a give-and-take thing, we use the import and export keywords to transfer modules from one file to another file or from one place to another place and so on. Hence, you don’t need to write the same code again and again.

Native JavaScript Modules

The good thing is that you can create modules in vanilla JavaScript now. Back in the day, modules could be made only using NodeJS, BabelJS, or a module bundler like Webpack or by accessing the libraries like React.

However, those days are gone! Now you can create and use JavaScript modules and work with them even in your front-end vanilla JavaScript environment without requiring to use any third-party tools.

Modules with Export-Import Syntax in Practice

[Recommended: Use VS Code Live Server Extension if you want to test run the codes below to avoid errors]

There are many different ways in which you can access and use modules practically.

First, open up your code editor and create a folder with some basic HTML and JS files like so:

|-js_modules
   |--index.html      
   |--app.js         // main script file
   |--module.js      // module file

Now, inside the index.html file, we’ve to write this :

<head>
    <title> JS Modules</title>
</head>
<body>
    <script type="module" src="./app.js"></script>
</body>

In the above code we’ve given a title and linked our app.js file which in this case is our main JavaScript file. Note that we’ve have added a keyword here called type=”module”. This is very important because this particular keyword helps us recognise our JavaScript Module setup and activates the module using Export-Import functionality.

Let’s now explore and create JS modules in different ways using different examples :

Example 1

This is the most basic way to export module features (from module.js file) and import them inside of your script (or the main file).

We’ll first write some simple functions :

export function squareThisDigit(x) {
    return x = x * x;
}

export function sumOfNumbers(a, b) {
    return a + b;  
}

Basically in the code above, we’ve created two simple JS functions and we’ve added an export keyword to both of them. So now, these functions inside the module are ready for export.

Now, we’ll type this inside the main JS file :

import { squareThisDigit, sumOfNumbers } from './module.js';

console.log(squareThisDigit(6));
// returns 36 to the console

console.log(sumOfNumbers(5,3));
// returns 8 to the console.

Here above, we’ve imported both the functions manually by using the import keyword from the module.js file and then called the functions individually.

You can import as many features (or functions) as you like by simply adding a comma(,) as shown in the above code.

Example 2

Here’s another easier way to simplify the code from Example 1 :

function squareThisDigit(x) {
    return x = x * x;
}

function sumOfNumbers(a, b) {
    return a + b;  
}

export { squareThisDigit, sumOfNumbers };

In the code block above, we have exported all the functions at-a-go by using the syntax export { function1, function2 } separated by a comma(,). Here also, we can write any number of functions (or other methods) and export them all at once to the main script file.

Now, when we import and run the functions inside the main JS file we get this:

import { squareThisDigit, sumOfNumbers } from './module.js';

console.log(squareThisDigit(9));
// returns 81 to the console

console.log(sumOfNumbers(23,3));
// returns 26 to the console.

Example 3 (The export default)

Here’s another neat way :

export default function allLargeCaps() {
    console.log('THIS IS IT!')
}
// we've used a default export syntax here

We can only have one export default inside a single module. More than one export default syntax inside a single module (module.js page in this case) is not allowed.

Now, let’s import the above code :

import { default as theMsg } from './module.js';

theMsg();

//-----------------OR-------------------------

import theMsg from './module.js';

console.log(theMsg());

// we've imported the function and named it 'theMsg'

In the code above, we’ve imported the function by giving it a new name theMsg and then called it. So, the function becomes theMsg() from allLargeCaps().

Example 4

Here, we’ve written the following codes. Below is the fourth way to get your job done :

const firstMessage = 'Hello World!';

const secondMessage = 'Hello My Friends!';


export { firstMessage, secondMessage };
import * as allMessages  from './module.js';

//giving our own custom name called 'allMessages' to the variables

console.log(allMessages.firstMessage);
// prints 'Hello World!' to the console

console.log(allMessages.secondMessage);
// prints 'Hello My Friends!' to the console

This example is all about giving your module a custom name and then calling it in a manner provided above.

Example 5

In this example we’re going to change names of functions and variables in the import statement like so :

const nameDisplay = 'Ritesh Deshmukh';


function sumOfNumbers(x, y) {
    return x + y;
}

export { nameDisplay, sumOfNumbers }
import { nameDisplay as Actor, sumOfNumbers as Result }  from './module.js';


console.log(Actor);
console.log(Result(5,8));

You can clearly see that we’ve changed the variable name from nameDisplay to Actor and sumOfNumbers function to Result in this example. So, from here on you have got to write the changed name.

How Module Aggregation in JavaScript Works

Simply speaking, what Module Aggregation does is that it exports and imports JS features or codes through a bridge.

Let’s first understand this in theory. Say, your fellow carpenter(from the example in the beginning) wants to pass on the hammer to you. He sits a little bit further away from you, so he passes the hammer to another person sitting nearby him who eventually passes the hammer to you, the third carpenter. Here, the middle person acts as a bridge between you two. And, that’s exactly how module aggregation works in JavaScript.

We’ll see this practically in action now. Create a repository and make four new files :

|--New_Folder
   |--index.html
   |--source.js         
   |--destination.js          
   |--bridge.js

Write down the following codes in each of the files :

<!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> JS Modules Aggregation</title>
</head>
<body>
    <script type="module" src="./destination.js"></script>
</body>
</html>
export function myMessage() {
    console.log('The code is working!');
}
export { myMessage } from './source.js';
import { myMessage } from "./source.js";
myMessage();

// prints 'The code is working!' to the console

This is how it works – Source >> Bridge >> Destination.

That’s all what you need for now to get started with all the basics of modules.

Note: These codes can be copied and tested on your PC but you might get an error message to display what it prints to the console. To fix this use a live server (as in VS Code), or create a local web server of your own.


Posted

in

by

Tags:

Leave a Reply