DEV Community

daichitt
daichitt

Posted on

CommonJS and ES Modules

In Node.js, there are two distinct module management systems: CommonJS and ES Modules (ECMAScript Modules). The difference between the two code snippets you provided lies in these module systems.

1. CommonJS (const express = require('express'))

  • CommonJS is the default module management system in Node.js.
  • It uses require() to import modules.
  • When a file has a .js extension, Node.js treats it as a CommonJS module by default.
const express = require('express');
Enter fullscreen mode Exit fullscreen mode
  • This format has been the standard way of writing modules in the Node.js environment for a long time.

2. ES Modules (import express from 'express')

  • ES Modules (ECMAScript Modules) is a module system based on the latest JavaScript specification.
  • It uses import to import modules.
  • To use ES Modules, you typically use the .mjs file extension, or you need to set "type": "module" in your package.json file.
import express from 'express';
Enter fullscreen mode Exit fullscreen mode
  • ES Modules are the latest JavaScript standard and are supported in browsers and newer Node.js versions.

Key Differences

  • require() is used in CommonJS, while import is used in ES Modules.
  • Using ES Modules requires configuration (e.g., file extension or package.json settings).

  • CommonJS is an older, widely used module system that is still common in most Node.js projects, but ES Modules are gradually gaining popularity as the new standard.

Which system you should use depends on your project's requirements and compatibility needs.

Sample package.json

{
    "name": "sample PJ",
    "private": true,
    "version": "0.0.0",
    "type": "module", // ES Modules
    "scripts": {
        "dev": "vite",
        "build": "tsc; vite build",
        "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
        "preview": "vite preview",
        "deploy": "npm run build && firebase deploy --only hosting"
    },
    "dependencies": {   
        "react": "^19.0.0",
    },
    "devDependencies": {
        "@types/react": "^19.0.4",
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)