Imagine you have an index.js file in your NodeJS project where you have used five functions. However, two of these functions might also be used in other files. So, instead of one file, you create three files in your project:
Here, each of these Javascript files is a module, and the way to export classes/functions and import them is basically the module system. A module system allows us to split and include code and import code written by us or other developers whenever required.
These modules are not just the Javascript files that exist in your project; they can also be any external package you have installed as a dependency in your project. Also, NodeJS has some built-in modules like http, fs, etc., which are available along with installation and can be imported without adding any external dependencies.
Two module systems are used in Node.
You have read the kitchen-chef-waiter example in my previous blog; Similarly, if we compare modules with that, imagine CommonJS is an old big recipe book we needed to search and find a recipe, while ESM is a new aged digital app to see recipes.
CommonJS (CJS)
// Export module.exports = function SayHello() { console.log("Hello World!"); }; // Import const GetHello = require("./hello-script.js"); SayHello(); // "Hello World!"
ECMAScript Modules (ESM)
// Export export function SayHello() { console.log("Hello World!"); } // Import import { SayHello } from "./hello-script.js"; SayHello();
Key Difference in syntax:
CJS: module.exports / require
ESM: export / import
{ type: "module"; }
Sometimes, you can use ECMAScript modules but an old package you have imported is written in CommonJS. To handle these cases, we sometimes make sure the output Javascript code generated from the Typescript file comes in the common format, even though we have written the Typescript files in ESM format.
For this, we add the compilerOptions in the tsconfig.json of our project:
// Export module.exports = function SayHello() { console.log("Hello World!"); }; // Import const GetHello = require("./hello-script.js"); SayHello(); // "Hello World!"
What happens then:
module: "commonjs": Outputs JavaScript using the CommonJS module system, which uses require and module.exports.
target: "es6": Ensures that the output JavaScript uses ES6 syntax and features like let, const, and arrow functions.
Input Typescript code:
// Export export function SayHello() { console.log("Hello World!"); } // Import import { SayHello } from "./hello-script.js"; SayHello();
Output Javascript code:
{ type: "module"; }
The above is the detailed content of NodeJS Modules [Simple Explanation]. For more information, please follow other related articles on the PHP Chinese website!