When we write javascript code our application can grow big, that time we need split the code into modules. A module is a reusable piece of code that we can use in our application.
We will learn two module system in javascript.
- CommonJS – the module system for Node server.
- ECMAScript Modules – it is the standard format module system.
CommonJS
This module system is basically for the node server application. NodeJS uses it also it’s packages.
For example we use ExpressJS as a framework of NodeJS. As we told previously a module is a piece of code, so Express is a piece of code or module in order to use it we need to use the require
statement.
const express = require('express')
So this is the nodejs way to import a module. Let’s write a custom module.
function DBConnect() {
db.connect('...')
}
The DBConnect()
function connects database to our application. If we want to use it as a module first we need to export the DBConnect()
function.
// dbConnect.js
module.exports = function DBConnect() {
db.connect('...')
}
Export is done. Let’s import so that we can use it,
const db = require('./dbConnect')
db.DBConnect();
This is the CommonJS module system.
ECMAScript Module
ECMAScript Module System is the standard format to modularize javascript code. The browser never had a module system so the ECMAScript came for a solution. This module system is completely based on import
& export
.
Lets write an example,
export default function sum(arr) {
let sum = 0
for(let item of arr) {
sum += item
}
return sum;
}
By writing export default
we are exposing sum function as a default module. Let’s import this,
<script type="module">
import sum from './sum.js'
let items = [1, 2, 3]
let res = sum(items)
console.log(res)
</script>
We have to write type="module"
as it will treat as a ECMAScript Module System so we can use import
& export
.