Skip to main content

Understanding Javascript Modules - The Absolute Guide

Published 6 min readMarkdown
Understanding Javascript Modules - The Absolute Guide

You have most likely seen codebases with a lot of files and varying structures and just wonder in your mind why there are so many files or how they even get connected. How do they find their paths to themselves? Or actually, why have modules in the first place?

  • Why Modules?

Initially when javascript was introduced, it lacked modularization (the concept of modules and moduling). This means that back then, if you code, your code will not be seperated more neatly as it is nowadays. It was usually in a single file with a single global scope. This led to a few issues like scope pollution where you have to define variables and functions in the global scope which may in fact, at some point, result in issues like naming conflicts and so on. This also made reusing code in other scripts or projects unnecessarily hard.

  • What Modules Do We Speak Of?

Usually, depending on the javascript framework that a developer uses for a project, the type of module pattern adopted varies. Take for example, in most NodeJS projects, you'd be seeing a lot of CommonJS pattern and with React or Angular, you'd be natively using another called the ES Module pattern. However, there are a few others like the AMD (Asynchronous Module Definition) which are not so common anymore and consequently won't be discussed.

  • ES Module Pattern

The first one we'd be looking at is the ES Module pattern. This type of module pattern is commonly used in React with the keywords being mainly import, export and default. Export and default keywords allow you to "open up" part or whole script and make it available to other scripts. Take a look at the following line of code:

// this is `script.js` file

// Declaring an arrow function without exporting
const add = (a, b) => a + b;
const multiply = (a, b) => a * b;

// Declaring the same arrow function but now exported for other scripts to use
export const add = (a, b) => a + b;
export const multiply = (a, b) => a * b;

In the code above, you have the first two lines of code which are syntactically familiar and then the other two lines that include an extra keyword. This extra keyword is what makes the lines of code available, or better put, exportable - so other scripts in the project can make use of them. To use the add function in an index.js script, for example, you have to import it like this:

// index.js

import { add, multiply } from './script.js'
const num1 = add(9, 7)
console.log(num1) // 16

const num2 = multiply(2, 3)
console.log(num2) // 6

Now, something might seem a bit new up there if you're not so familiar with ES6 patterns and that is the curly braces. This is called destructuring in Javascript and it is available to both arrays and objects. Javascript treats modules like objects and that is why we can use this functionality meant for objects on it. It simply means to get something out of an object.

Regarding ES Modules, at other times, you might have an extra keyword that says default. This is usually employed when you have just one export from a file - a default - instead of, for example, two as in the previous example or even more. Take a look at this:

// index.js

export default const multiply = (a, b) => a * b;
const add = (a, b) => a + b

As you can see, right above here, you have just one of two functions exported as opposed to what we did in the first place where we exported two. In this case, we also have a little bit of a different way of importing it in other files where we might want to use it. take a look at this:

// script.js

import multiplyFunc from './index.js'
// console.log(multiplyFunc(3, 2)) will give 6

Now, what difference do you particularly notice between the first and second import up there and this? If you picked that right, it should be that we destructured in the first but we didn't do that in the second. Why? because we're dealing with just one variable inside a module and it made that just available without bothering to put it in an object. There are a few other use cases for a default export but this is the most important for now.

The last type you might also encounter in this type of moduling is the one that has to do with importing everything in a module all at once. In this case, you're doing something like you're packing all exported values in a module into a box and giving them a name so they can easily be used in other Javascript files. Take a look at this:

// script.js

export const add = (a, b) => a + b;
export const multiply = (a, b) => a * b;

In the script file, the two previously defined functions are here again and instead of importing by destructuring or like we did with the export default, we'll do a little bit of a different thing here. Look here in the import file, index.js

// index.js

import * as operators from './script.js'
const addedNum = operators.add(2, 3)
console.log(addedNum)
// addedNum is 9

The asterisk above denotes all exported variables from the specified path and the 'as' keyword is used to denote the name one would use to refer to it in the current file. To translate the code above, in this case, you are importing all exported values from the specified path, script.js, as package name operators. This package name becomes an object and that is why you're able to use the package's name dot whatever you want to pick like operators.multiply().

  • CommonJs Module Pattern

Another very common moduling pattern is the CommonJs module. This is more common in NodeJs codebases even though some would still rather use the ES Module - but with certain configurations. This is because NodeJs natively runs with CommonJs.

In CommonJs, to export a value, you can do that in one of these two ways:

// this is `script.js` file

// adding directly to the exports object
exports.add = (a, b) => a + b;

// creating a variable and adding to the export later on
const multiply = (a, b) => a * b;
module.exports = { multiply }

Both methods above are remarkably fantastic and easy to understand. Usually too, the second method is employed when you have just a single value to export but the same can be done when you have a lot of things to export too. In fact, both methods can be used when one has one thing to export or a lot of things to export. Each is independent of the other and so, either can be employed.

Importing these exported values is very simple too. All you have to do is require them and specify the path to the file that holds them. And the interesting thing about it is it is not as specific as the ES Pattern. Take a look at this:

// index.js

// Destructuring
const { add, multiply } = require('./script')

// requiring wholly
const operators = require('./script')
const addedNum = operators.add(3, 4)
console.log(addedNum) // 7

Personally, I prefer the CommonJs module even though a lot of people I know prefer the ES Module Pattern because of how detailed it can be.

You may find the ES Module Pattern easier, or better, compared to the CommonJs module so, you should rather use it in your projects instead of the CommonJs. Some are also commonly known with some frameworks and hence, to use anything different from them, you might want to configure some scripts. Until then, goodbye!

About the author

No comments yet. Be the first to comment.