Node.js6 min read

ES Modules in Node.js (import/export)

Learn modern ES modules syntax with import and export in Node.js. Understand the difference from CommonJS.

Sarah Chen
December 19, 2025
0.0k0

ES Modules in Node.js

ES Modules (ESM) is the modern JavaScript module system. Node.js supports it fully.

Enabling ES Modules

**Option 1:** Use .mjs extension ```javascript // math.mjs export function add(a, b) { return a + b; } ```

**Option 2:** Add "type": "module" to package.json ```json { "name": "my-app", "type": "module" } ```

Now .js files use ESM: ```javascript // math.js (with "type": "module") export function add(a, b) { return a + b; } ```

Named Exports

```javascript // utils.js export function formatDate(date) { return date.toISOString(); }

export function capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1); }

export const VERSION = '1.0.0'; ```

```javascript // app.js import { formatDate, capitalize, VERSION } from './utils.js';

console.log(capitalize('hello')); // Hello console.log(VERSION); // 1.0.0 ```

Default Export

```javascript // User.js export default class User { constructor(name) { this.name = name; } } ```

```javascript // app.js import User from './User.js'; // No curly braces

const user = new User('Alice'); ```

Mixed Exports

```javascript // api.js export default function fetchData() { /* ... */ } export const BASE_URL = 'https://api.example.com'; export function formatResponse(data) { /* ... */ } ```

```javascript // app.js import fetchData, { BASE_URL, formatResponse } from './api.js'; ```

Import Everything

```javascript import * as utils from './utils.js';

utils.formatDate(new Date()); utils.capitalize('hello'); console.log(utils.VERSION); ```

CommonJS vs ES Modules

| Feature | CommonJS | ES Modules | |---------|----------|------------| | Syntax | require/module.exports | import/export | | Loading | Synchronous | Asynchronous | | File extension | .js | .mjs or "type": "module" | | Top-level await | ❌ | ✅ |

Importing CommonJS in ESM

```javascript // ESM file importing CommonJS import express from 'express'; // Works!

// Named imports might not work import { Router } from 'express'; // May fail const { Router } = express; // Use this instead ```

File Extensions Required

ESM requires full file paths: ```javascript // ❌ Won't work in ESM import { add } from './math';

// ✅ Works import { add } from './math.js'; ```

Key Takeaway

ES Modules is the modern standard. Use `export` to share code, `import` to use it. Enable with `"type": "module"` in package.json or .mjs files. Remember to include .js extensions in imports!

#Node.js#ES Modules#import#export#Beginner