Wednesday, June 05, 2024

Key Differences in Code Organization, CommonJS and ES6 Module Formats in Node.js

For every beginner starting to learn and use the Node.js platform, regardless of their level of JavaScript knowledge, it can be very confusing that Node.js uses both CommonJS and ES6 module formats. And when you're asked about the ES7 specification of the scripting language, I think that's the first thing that needs to be explained. CommonJS initially emerged as a project to standardize the module ecosystem for the JavaScript programming language outside of web browsers. The CommonJS specification on how modules should work is widely used today for JavaScript on the server-side with the Node.js platform, but it is also used for JavaScript on the client-side. However, that code needs to be bundled with a transpiler since browsers do not support CommonJS. So, CommonJS is an older standard used in the Node.js platform for the module format and is now treated as the default.

Most built-in modules are created in the CommonJS module format. With the advent of ECMAScript 2015, or ES6, the module format became a significant improvement for the entire JavaScript programming language world, as well as for newer versions of the Node.js platform. Today, Node.js supports both CommonJS and ES6 module formats, and although both module formats are conceptually similar, they differ significantly in practice. Regarding the newer ES7 module format in the Node.js platform, such a thing does not exist because ES7 did not bring any new changes to the module format; rather, ES7 mainly focuses on other language features. What will change in the future, we can only speculate for now; but until then, the current support for the Node.js platform relies exclusively on CommonJS and ES6 module formats. The ES6 module format is becoming increasingly popular and a better choice for newer projects, especially in newer Node.js versions, but CommonJS is definitely still in use.

A Programmer Drinks Coffee and Thinks Before Continuing Coding

A Programmer Drinks Coffee and Thinks Before Continuing Coding

Regarding the difference between CommonJS and ES6 module formats in Node.js, the first difference is that CommonJS modules must be loaded from a module repository, such as npm. Secondly, CommonJS modules can only be accessed from the context of a Node.js application. CommonJS modules do not have exports or prototypes like ES6 modules do. Finally, the `require` function in CommonJS is not equivalent to the `import` function in ES6 modules. The main difference between CommonJS and ES6 modules is the folder structure. With CommonJS, all project dependencies are stored in a single folder called `node_modules`. With ES6 modules, each dependency is stored in its own files. This allows developers to better control how their dependencies are used and facilitates software versioning. But you should also know that CommonJS is a module system inspired by Microsoft’s AMD API.

It allows modules to be written similarly to AMD modules, with the main difference being that CommonJS modules can be loaded in any Node.js environment. ES6 modules are a new module system developed by Google that enables greater modularity and reusability across different programming languages. The advantage of using ES6 modules is that they can be translated into native code, making them faster and more efficient than CommonJS modules. However, the most important thing for any beginner regarding the Node.js platform is simply that CommonJS supports dynamic module loading, meaning you can import modules during program execution. Module loading in CommonJS is synchronous, which means it is blocking. This can lead to performance issues in some situations. Variables defined within a module are private and invisible outside the module, achieving local scope.

However, ES6 represents a significant update to the JavaScript programming language, bringing numerous new functionalities and improvements. Notably, arrow functions provide a shorter and more readable way to define functions while maintaining the value of `this` within the function to the value that was current when the function was defined. ES6 allows for the destructuring of objects and arrays to easily extract data and also introduces promises for better handling of asynchronous operations instead of using callback functions. We could list differences endlessly, but it’s best to recognize them through practice and using both module formats in Node.js.

Step by Step: How to efficiently port CommonJS code to ES6 modules

This question is not only excellent, but it hints at the start that in some cases, with a change file extension and a bit of syntax can be passed from one format module to another. You will definitely notice the difference with this kind of practice. Go back to the previous lesson 2 and see how we created the CommonJS module format, see here. So that you don't write the same code again; when you start a project in Visual Studio Code; simply copy the lesson2 directory to the same main node_js_tutorial directory and rename it to lesson3. Then rename the following files and their extensions; lesson2.js to lesson3.mjs and app.js to app.mjs. Now all you have to do is change the JavaScript code a little. Open the file lesson3.mjs and change the following.

// a variable for the internal use

// var count = 0;

let count = 0;

// a function which use the variable for the internal use

// const next = function() { return ++count; };

const next = () => ++count;

// a constant for the external use

const PI = 3.14;

// a function for the external use

const sum = (num1, num2) => num1 + num2;

// a class for the external use

class Student {

    // constructor

    constructor(fname, lname, subject) {

        this.fname = fname;

        this.lname = lname;

        this.subject = subject;

    }

    // method

    introduction() {

        console.log(`Hello! My name's ${this.fname} ${this.lname}, and I study ${this.subject}.`);

    }

}

/*

module.exports.next = next;

module.exports.PI = PI;

module.exports.sum = sum;

module.exports.Student = Student;

*/

// module.exports = { sum:sum, PI:PI, Student:Student, next:next }

export default {sum, PI, Student, next};

As you can first see from the above JavaScript code, the ES6 module format uses the let keyword instead of var to declare variables like count in this case. Arrow functions provide a shorter and more readable way to define functions, so the next() function can also be shortened in this case. And at the end of the file, instead of the module.exports structure, we use export default; but also template strings allow easy inclusion of variables in a string literal, which improves readability and avoids the need for string concatenation. Open the app.mjs file, and change the following:

// const lesson2 = require('./lesson2');

// Importing the module

import lesson3 from './lesson3.mjs';

console.log(lesson3);

// Creating an instance of thr Student class

const person1 = new lesson3.Student('Manuel''Radovanovic''Computer Science');

// Logging the instance

console.log(person1);

// Calling the introduction method

console.log(person1.introduction());

// Logging the values from the module

console.log(lesson3.PI);

console.log(lesson3.sum(5,10));

// Calling the next function from the module

console.log(lesson3.next());

console.log(lesson3.next());

console.log(lesson3.next()); 

When we talk about the ES6 module format, we definitely mean loading the module using the import function instead of require, which is used by the CommonJS module format. Everything else will work the same, but we've commented this simple JavaScript code to make things clearer for you. Now simply type the following command in the terminal panel.

manuel@manuel-virtual-machine:~/nodejs_tutorial$ node lesson3/app.mjs

You will get the following result.

{

  sum: [Function: sum],

  PI: 3.14,

  Student: [class Student],

  next: [Function: next]

}

Student {

  fname: 'Manuel',

  lname: 'Radovanovic',

  subject: 'Computer Science'

}

Hello! My name's Manuel Radovanovic, and I study Computer Science.

undefined

3.14

15

1

2

3

You can see how we did all this and how it all looks in the following video. 

Node.js - 2. How to Change CommonJS in ES6 Format Module?




















 

 

No comments:

Post a Comment