Table of contents
Modules In JavaScript
A module is a function or group of similar functions. They are grouped together within a file and contain the code to execute a specific task when called into a larger application.
Advantages Of Using Modules
Independent/Self-contained: A module has to be as detached from other dependencies as possible.
Specific: A module needs to be able to perform a single or a related group of tasks. The core essence of creating them in the first place is to create separate functionalities. One module, one (kind of) task.
Reusable: A module has to be easy to integrate into various kinds of programs to perform its task.
Instead of having all of those unrelated programs together in one module/file, it is a better practice to create several files, or modules, for each of those tasks. In such a case, the modules become dependencies.
Then from the main app or program, you simply import/load the dependencies (i.e the modules you need) and execute them accordingly. As a result, your main app becomes cleaner and more minimal.
Assuming you need to process payments in some other application in the codebase, for example, it becomes very easy to reuse the same functionality. No need to copy and paste or code a new function from scratch
In JavaScript, we use the
import
andexport
keywords to share and receive functionalities respectively across different modules.The
export
keyword is used to make a variable, function, class or object accessible to other modules. In other words, it becomes a public code.The
import
keyword is used to bring in public code from another module.
Using Modules In Node
To include a module, use the
require()
function with the name of the module.When use require it will execute the file inside the module which we are exporting
But if we want to use some part of the code then we need to export it
To include a module, use the
require()
function with the name of the module.console.log(module) // { // id: ".", // path: "...", // exports: {},--------this is what we are looking for // parent: null, // filename: "...", // loaded: false, // children: [], // paths: [ // ... // ], // }
Node Js uses common js
We need to mention the function/element which we want to be used in other files