Modules in JavaScript

Akshat Chaturvedi
Last Updated: May 13, 2022

Introduction

 

Suppose you wrote some functions in a JavaScript program. Now you want to use these functions in another JavaScript program. Instead of writing the functions again in the new script, you can import the functions from your previously written program into our new script.

 

JavaScript supports importing of methods from one program to another.

 

Let’s explore modules in JavaScript with a working example:

 

In this example, we’ll first create a canvas on our HTML page. Then on that canvas, we’ll draw two squares or rectangles. One square will be of fixed shape, size, color, and we’ll fix its position on the canvas, whereas the next square will be of a random shape, size, and color, the position of the second square will also be random on the canvas.

 

Working of the program

 

  • Our main working directory will have one HTML file - ‘index.html,’ one javascript file - ‘index.js’ and a folder named ‘modules.’
  • The modules folder will contain two javascript files, ‘canvas.js’ and ‘square.js.’

 

Caption: Directory Structure

 

  • First of all, in our HTML file, we’ll write some basic boilerplate code and include the index.js as module type in the script tag.

Also, we’ll style the canvas element with a black border.

 

index.html

 

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Modules Demo</title>
<style>
canvas {
border: 1px solid black;
}
</style>
<script type="module" src="index.js"></script>
</head>
<body>


</body>
</html>

 

 

  • Now, in our modules folder in the square.js file, we’ll create some functions.
    • draw() - This function will draw a square on the canvas with a given length, color, and x-y coordinates.
    • random() - This function will give us a random number from the provided range of numbers.
    • reportArea() - A function to calculate the area of the square.
    • reportPerimeter() - A function to calculate the perimeter of the square.
    • randomSquare() - This function will generate a square with a random color, random x-y coordinates, and random length.

 

After creating these functions, we’ll have to export these by giving the export command (check syntax below) to use in some other program.

 

/modules/square.js

 

const name = 'square';


// Function to draw a square on the canvas with given length, color and x-y coordinates
function draw(ctx, length, x, y, color) {
  ctx.fillStyle = color;
  ctx.fillRect(x, y, length, length);


  return {
    length: length,
    x: x,
    y: y,
    color: color
  };
}



// Generating a random number from provided range of numbers
function random(min, max) {
   let num = Math.floor(Math.random() * (max - min)) + min;
   return num;
}



// Calculating area of square and adding it to the list
function reportArea(length, listId) {
  let listItem = document.createElement('li');
  listItem.textContent = `${name} area is ${length * length}px squared.`


  let list = document.getElementById(listId);
  list.appendChild(listItem);
}



// Calculating perimeter of square and adding it to the list
function reportPerimeter(length, listId) {
  let listItem = document.createElement('li');
  listItem.textContent = `${name} perimeter is ${length * 4}px.`


  let list = document.getElementById(listId);
  list.appendChild(listItem);
}



// Generating a random rectangle
function randomSquare(ctx) {
  let color1 = random(0, 255);
  let color2 = random(0, 255);
  let color3 = random(0, 255);
  let color = `rgb(${color1},${color2},${color3})`
  ctx.fillStyle = color;


  let x = random(0, 480);
  let y = random(0, 320);
  let length = random(10, 100);
  ctx.fillRect(x, y, length, length);


  return {
    length: length,
    x: x,
    y: y,
    color: color
  };
}



// Exporting functions
export { name, draw, reportArea, reportPerimeter };
export default randomSquare;

 

 

  • The canvas.js file will also contain some functions that will be used to create canvas elements and manage the reportList.

(We will be displaying the area and perimeter of a square below the canvas, so here the reportList will contain the text elements to show perimeter and area)

 

The functions inside this file are:

  • create() - This function will create a canvas of a given height and width. After creating it will append this to an HTML parent element with the given id.
  • createReportList() - This function will create the list used to display the area and perimeter of the square (like we discussed above).

 

Here also, we’ll need to export these functions to use them outside this program.

 

/modules/canvas.js

 

// Function to create a canvas of certain height-width 
// The parent element and its id is also provided as parameter
function create(id, parent, width, height) {
  let divWrapper = document.createElement('div');
  let canvasElem = document.createElement('canvas');
  parent.appendChild(divWrapper);
  divWrapper.appendChild(canvasElem);


  divWrapper.id = id;
  canvasElem.width = width;
  canvasElem.height = height;


  let ctx = canvasElem.getContext('2d');


  return {
    ctx: ctx,
    id: id
  };
}


// Creating a report list to display perimeter and area of square
function createReportList(wrapperId) {
  let list = document.createElement('ul');
  list.id = wrapperId + '-reporter';


  let canvasWrapper = document.getElementById(wrapperId);
  canvasWrapper.appendChild(list);


  return list.id;
}


// Exporting functions
export { create, createReportList };

 

  • Finally, coming on to our main JavaScript file, index.js.

At the beginning of our file, we’ll first import the required functions from their respective locations.

For example, the line - import { create, createReportList } from './modules/canvas.js'; imports the create() and createReportList() method from the canvas.js file.

‘./’ this specifies the current working directory, hence ‘./modules/canvas.js’ means that we’ll search for the modules folder in our current directory and then search for canvas.js in the modules folder.

 

After importing the necessary methods, we’ll create a canvas and a reportList using the methods we imported earlier and create two squares (one fixed and one random).

 

index.js

 

// Importing the functions from the previous java programs
import { create, createReportList } from './modules/canvas.js';
import { name, draw, reportArea, reportPerimeter } from './modules/square.js';
import randomSquare from './modules/square.js';


// Creating a canvas on the html page
let myCanvas = create('myCanvas', document.body, 480, 320);
let reportList = createReportList(myCanvas.id);


// Creating a fixed square at fixed coordinates
let square1 = draw(myCanvas.ctx, 100, 50, 100, 'red');
reportArea(square1.length, reportList);
reportPerimeter(square1.length, reportList);


// Random square
let square2 = randomSquare(myCanvas.ctx);

 

 

Output

 

Caption: Displayed HTML page

 

Caption: Displayed HTML page

 

As you can see on the web pages above, one square is fixed, and the other will keep changing its shape, size, color, and position with each reload.

 

Frequently Asked Questions

 

  1. What are the advantages of using Modules?

Some of the benefits of using modules in our project are:

  • Different functions are present in separate files, so the overall code becomes easier to maintain. We can easily find and make changes in a particular function without affecting the code of other modules.
  • Reusability increases, which means that we can now use the same functions in many different programs without having to write the functions again & again.

 

2. How to import a function from some other program in JavaScript?

We can import the functions from other JavaScript files into our program by simply giving the function names in curly braces and the location of the JavaScript file from which we want to import.

 

// Importing create() and createReportList() function from the cavas.js file


import { create, createReportList } from './modules/canvas.js';

 

3. What is the syntax to export and import with renaming?

In JavaScript, we can also change the name of the import functions. Usually, we change the name when there is a function with the same name in our program. So to avoid any conflicts, it is better to import the function with a custom name.

 

 

// Importing with custom names
import { create as make, createReportList as makeList } from ‘./modules/canvas.js';



// Exporting with custom names
export {
    myFunction1 as create,
    myFunction2 as createReportList
}

 

 

4. What is the default export in JavaScript?

Each program in JavaScript can have one default export function. This function can be imported without using curly braces, and if you try to import a function not present in the script, then the default export function is imported by default.

 

In my square.js file, I have made randomSquare() as my default export function

function randomSquare(ctx) {
   // Function Body
}


// Exporting by default
export default randomSquare;

 

 

5. What is the syntax to import all functions at once from a given script?

We can import all functions from a given program by writing * in place of function names.

 

import * as square from ‘./modules/square.js’


let square1 = square.draw(myCanvas.ctx, 100, 50, 100, ‘red’);
square.reportArea(square1.length, reportList);

 

 

Key Takeaways

 

In this blog post, we saw and discussed modules in JavaScript and how much it is beneficial for us. We also looked at a working example of modules in JS.

 

The concept of implementing modules in your web development project is very crucial because nowadays, all tech giant companies are using Modular Programming because of its many advantages.

 

So, congratulations for making it this far. If you understood the blog clearly, then you can easily incorporate modules into your JavaScript project.

 

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think