ES6 JavaScript Modules : The Simplest Explanation From Scratch

·

4 min read

ES6 JavaScript Modules : The Simplest Explanation From Scratch

Why Modules?

CommonJS was one of the earliest module systems to gain popularity in JavaScript, especially in server-side environments like Node.js.AMD (Asynchronous Module Definition) came next and was designed primarily for the browser environment.ES6 Modules, which were introduced in the ECMAScript 2015 (ES6) standard, are the newest and most widely accepted way to handle modules in JavaScript. They are built right into the language and are the preferred choice for organizing code in modern web development, whether you're working in web browsers or on server-side platforms like Node.js. If feature of modules have never been introduced we had to use numerous script tags in HTML file,The most common problems of this approach are :

1) Dependency: With this approach, all scripts are dependent on each other. Loading the scripts using the script tag should be in the correct order if it's not then, it can lead to code-breaking mishaps.

// export.js

const variableName = "Hey I'm a variable" ;

function functionGreeting (personName) {
    console.log(`Hello ${personName}`);
}
// import.js

console.log(variableName);

const personName = 'Roni Dey' ;
functionGreeting(personName) ;
<!-- modules.html -->
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Modules</title>
</head>
<body>

    <!-- html code -->

    <script src="export.js"></script>
    <script src="import.js"></script>

</body>
</html>

So, here we can see we have two Javascript files export.js and import.js.And in modules.html we load these scripts using the script tag. But this is order sensitive. Here in that case internally export.js will be loaded first before import.js as it comes first in order.

So here the output will be :

Hey I'm a variable

Hello Roni Dey

And if these scripts were in a different order

<script src="import.js"></script>
<script src="export.js"></script>

Then it gives :

Uncaught ReferenceError: variableName is not defined.

2) Namespacing: There is another problem that comes up with this approach that is all variables from different files are shared and can accidentally overwrite each other. So we have to be careful when naming a variable. We can't use variableName as a variable name again in impost.js though this variable name is used in another file. So in bigger projects, it may cause trouble.

// import.js
const variableName = "Hey I'm a variable";
console.log(variableName);

const personName = 'Roni Dey' ;
functionGreeting(personName) ;

It gives us an error. As variableName is used in another file. So in bigger projects it's difficult to remember all the variable names and also those are created on other files.

3) Code Organization: In bigger projects developers have to deal with many scripting files. So loading scripts using numerous script tags makes the code messy and hard to manage. Loading them in the correct order and naming the variable properly would become a big challenge for maintainers and future contributors.

To overcome this problem, we have one solution and that is not to load all the scripts except one main script through the script tag. Then how do we access all the variables created in other files? That's where modules comes in.

ES2015 Module Syntax

ES6, which stands for ECMAScript 2015, made JavaScript even better by introducing a system for modules. This module system enables you to create reusable code in distinct files and then import these files into other parts of your codebase. Here's how you use ES6 modules:

Exporting :

We can export variables, functions, or classes from a module which are required using the export keyword.

// export.js
export const variableName = "Hey I'm a variable" ;

export function functionGreeting (personName) {
    console.log(`Hello ${personName}`);
}

// default export
export default const var1 = 42;

or can export an item after changing its name.

const variableName = "Hey I'm a variable" ;
export { variableName as newVariable };

Importing :

We use the import statement to import required items to a file from another file.

// import.js
import var1, { variableName, functionGreeting } from './export.js';

console.log(variableName);

const personName = 'Roni Dey' ;
functionGreeting(personName) ;

Importing an item and changing its name :

// import.js
import var1, { variableName, functionGreeting as newFunction } from './export.js';

console.log(variableName);

const personName = 'Roni Dey' ;
newFunction(personName) ;

Changing the HTML :

Now we don't need to load all the scripts as we can access all the require items from any scripting file using modules. We modify html script tag using type="module" property, which should be attached to the main script.

<script src="import.js" type="module"></script>

Conclusion

ES6 modules provide a more organized and efficient way to structure your JavaScript code, especially in large applications. It provides the ability to load pieces of code on-demand, which can boost your application's speed by fetching and using code precisely when it's necessary. This efficient loading approach minimizes the time it takes for your web page to initially load, ensuring a quicker and more responsive user experience.