Basic Usage of CommonJS and ECMAScript Modules

Basic Usage of CommonJS and ECMAScript Modules

A Beginner's Guide to Using and Comparing CommonJS and ES Modules with Examples

·

2 min read

CommonJS

CommonJS modules are the original way to package JavaScript code for Node.js.

Each file is a module with its own scope. Variables, functions, and classes defined in a file ar

e private and not visible to other files.

Inside each module, the module variable represents the current module.

The module variable is an object, and its exports property (i.e. module.exports) represents the interface that the current module exposes externally.

When other files load this module, they actually read the module.exports of this module.

// module.js
const uri = "<connection string uri>"

module.exports = uri
// main.js
const uri = require("./module")

console.log(uri)
// module.js
let config = {
  tv_series: "Person of Interest",
  season: 1
}

let printConfig = (config) => {
  console.log(`--- ${config.tv_series}: Season ${config.season} ---`)
}

let name = "John"

let greet = () => {
  console.log("Hey.")
}

let greetWithName = (name) => {
  console.log(`Hey ${name}.`)
}

// module.exports.config = config
// module.exports.printConfig = printConfig
// module.exports.name = name
// module.exports.greet = greet
// module.exports.greetWithName = greetWithName

module.exports = {
  config,
  printConfig,
  name,
  greet,
  greetWithName
}
// main.js
let { config, printConfig, name, greet, greetWithName } = require("./module")

printConfig(config)

greet()

greetWithName(name)

ECMAScript Modules (ESM)

  1. Add "type": "module" in our package.json file. This will tell Node.js to treat all .js files in our project as ES modules.

     {
       "type": "module"
     }
    
  2. Use the .mjs file extension for our ES modules

// module.mjs
export const uri = "<connection string uri>"
// main.js
import { uri } from "./module.mjs"

console.log(uri)
// module.mjs
let config = {
  tv_series: "Person of Interest",
  season: 1
}

let printConfig = (config) => {
  console.log(`--- ${config.tv_series}: Season ${config.season} ---`)
}

let name = "John"

let greet = () => {
  console.log("Hey.")
}

let greetWithName = (name) => {
  console.log(`Hey ${name}.`)
}

export {
  config,
  printConfig,
  name,
  greet,
  greetWithName
}
// main.js
import { config, printConfig, name, greet, greetWithName } from "./module.mjs"

printConfig(config)

greet()

greetWithName(name)