JS Modules Cheatsheet ๐
As JavaScript grew, managing code became a task. Earlier code was written in a single file, this is good when the code is small but for larger code base it is not a good practice. Why?
Code becomes hard to read and navigate
There can be naming conflicts, when we name functions, variables, objects, etc.
Debugging will also become hectic.
If we handle UI, API calls, backend in a single file, maintaining and scaling the application will become a challenge. That is why we use modules.
A JavaScript module is a small piece of code that can be used anywhere in your code. A module file is a .js file using import/export. It makes the code easier to understand since all components of the code are no longer together. By using modules, our keep is kept organised at one place and reused at different parts of our project.
Why modules are needed?
Modules allow you to split your code into smaller and manageable sections, these sections can be reused anywhere in your code. Each module is different and holds different parts of your code that has specific responsibilities. So instead of one massive bulky file your project you have a collection of well organised code files. Making modules prevents developers from having naming conflicts. Also, each module has a private scope, only those elements that are specifically exported using the 'export' keyword are publicly exposed, this allows the data to not be authorised without permission and reduces the risk of bugs.
Types of modules:
CommonJS modules are used in NodeJS environment. Developers use module.exports to export functions, variables or objects from a module. Other modules access these exports using a require() function and module.exports to share them. Modules are loaded synchronously, which means execution waits until the module is fully loaded, making it better for the server side.
ES6 Modules use import and export keywords. Putting setting type : "module" in the package.json tells NodeJS to treat .js files as ES6 modules, enabling import and export. ES modules are asynchronous in nature therefore they are better for the browser side.
ES6 modules are modern and used for both the browser as well as the modern Node.js. CommonJS can import ES6 modules using await import( ), ES6 modules can also import CommonJS but cannot use require.
Exporting functions or values vs Importing Modules
To make code available outside the designated file, export is used.
To use exported code in another file, import is used.
Eg. we have a file named math.js
export const add = (a, b) => a+b;
export const multiply = (a, b) => a*b;
we have another file named app.js
import {add, multiply} from './math.js'
console.log(add(3,4)); // output comes out to be 7
console.log(multiply(5,6)); // output comes out to be 30
We used export so that values of math.js can be used in another file app.js.
Different ways of exporting and corresponding ways of importing the exported items:
- Name Export: multiple items can be exported by name. But hwile importing exact names should be used.
Eg. We have a file name.js
export const name = "ansh";
import {name} from './name.js' into another file
so if I console.log(name); //output will be ansh.
If there is no name, no export will be done.
- Default Export: No name is needed to export or import an item. Each module has 1 default export. Any name can be used to import it.
Eg. export default 'ansh';
import hahaha from './name.js'
console.log(hahaha); //output is still going to be ansh
- We can also combine Default+Name export.
Eg. export const name = 'ansh'
export default 'ansh'
import hahaha, {name} from './name.js'
Default vs Named exports
There is no conclusion to this debate, different developers different point of views.
But using name exports will give you the surety. Let us understand thing via an example, I have a warehouse from where materials have a clear label on them like shoes, sandals, slippers, etc. if the delivery person will ask for shoe instead of shoes he will not get it. Here, many items can be sent but the request should be made using the exact name only.
Now imagine, the warehouse sends a big box to a shop with nothing on it so the receiver can call it anything, mystery box, big box, product container, etc. It is the same box with different names. Here only one item is shared with no fixed name, the receiver chooses the name he thinks fit.
Some developers would want to be specific some would not.
Benefits of modular code
Better code organisation can be done since instead of one colossal-messy code file, code is split into meaningful chunks.
When code is split, changes and debugging is easier and faster, making changes in one file will not affect any other file.
There will be increased reusability of your code. In the current app as well as other projects. You wrote a piece of code once and are now using it at different place saving your time and increasing your efficiency.
In cases of working with a team, using modules makes the work hassle free, one developer works in one file while another one works on another file, there is no unnecessary conflicts or no one overwrites anyone's code.
Naming issues do not emerge.
Easier scalability.
Take modules as different cupboards in the kitchen. If there is only one cupboard utensils, spices, ingredients everything will be placed in one place ๐ ๐ปโโ๏ธ
But if different cupboards are made, each item is placed in their designated section, making each cupboard look clean and there is no hassle in finding stuff.
Therefore, modules are a fundamental part of modern JavaScript, if you want to build something big, you will have to use the modules, there is no other option.