Common Js and Modules in JavaScript/ Node js World

Common Js and Modules in JavaScript/ Node js World

You never get confused with commonjs and Es modules, never.

Old Way - Common Js

// import
const express = require('express')

// export
module.export = express

New Way- Modules

// import
import express from 'express

// export
export default express

Distracted Boyfriend Meme | FILES; MODULES | image tagged in memes,distracted boyfriend | made w/ Imgflip meme maker

Modules is a fancier name for Files. It is that simple.

Common Js is the original way to package code in node js. Node js also supports the Ecma Script modules(import/ export syntax).

Package code meaning, putting larger code in different-different files and and accessing them as you need.

For example, you can divide controllers, models, routes and you views in different different files inside multiple folders and you can access them using two ways,

Common js(old)

Es modules(NEW)

Es modules is Ecma script standard modules as we use to package code in our frontend application and access them using import export syntax. This is cool, right?

Here is both way with example:

Common js -

file: sum.js
function sum(a,b) {
    return a + b

modules.export = calculate
file: calculator.js
const sum = require('sum')
function calculator() {
    const sumResult =  sum(23, 55)
    console.log(sumResult)

calculator()

Es Modules

file: sum.js
function sum(a,b) {
    return a + b

export default sum
file: calculator.js
import sum from './sum.js'  // Es Modules sum is in same directory
function calculator() {
    const sumResult =  sum(23, 55)
    console.log(sumResult)

calculator()

Keep in mind:

You can change Your code behavior using package.json type field

{
  "name": "backend",
  "version": "1.0.0",
  "description": "Backend of Online Examination System",
  "main": "index.js",
// you can use import and export syntax of Ecma script this way
  "type": "module", // module - Treated as Ecma Script modules Es Modules
  "scripts": {
    "start": "node -r dotenv/config index.js dotenv_config_path=backend.env",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "dotenv": "^16.4.5",
    "express": "^4.19.2"
  }
// change type field to commonjs to change the behaviour to default,
// you can omit this too, this is default way
 "type": "commonjs", // commonJs - default modules of Node js

Thank You for reading, If you like this post, Share it, also give it a like, follow for more such sort and concise post in the future.