惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
D
Docker
Microsoft Security Blog
Microsoft Security Blog
Google DeepMind News
Google DeepMind News
M
MIT News - Artificial intelligence
P
Proofpoint News Feed
Engineering at Meta
Engineering at Meta
Y
Y Combinator Blog
Vercel News
Vercel News
F
Fortinet All Blogs
B
Blog
Recent Announcements
Recent Announcements
A
About on SuperTechFans
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - Franky
MongoDB | Blog
MongoDB | Blog
Stack Overflow Blog
Stack Overflow Blog
B
Blog RSS Feed
C
Check Point Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
V
Visual Studio Blog
月光博客
月光博客

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
JavaScript Modules: The 2026 Guide (ESM vs CommonJS)
Alex Chen · 2026-05-16 · via DEV Community

Alex Chen

JavaScript Modules: The 2026 Guide (ESM vs CommonJS)

Stop confusing require and import. Here's the complete picture.

Two Module Systems

CommonJS (Node.js legacy)    ES Modules (Modern standard)
─────────────────────         ───────────────────────────
require()                    import
module.exports               export
Synchronous                  Asynchronous
Node.js default              Browser + Node.js
.cjs extension               .mjs extension

Enter fullscreen mode Exit fullscreen mode

CommonJS (CJS)

// math.js
function add(a, b) { return a + b; }
function multiply(a, b) { return a * b; }

module.exports = { add, multiply };

// Or single export:
// module.exports = function() { ... };

// app.js
const { add, multiply } = require('./math');
const utils = require('./utils'); // Import everything

console.log(add(2, 3)); // 5

Enter fullscreen mode Exit fullscreen mode

ES Modules (ESM) — Use This!

// math.mjs (or math.js with "type": "module" in package.json)
export function add(a, b) { return a + b; }
export function multiply(a, b) { return a * b; }

// Named exports (recommended for utilities)
export const PI = 3.14159;

// Default export (one per file — for main class/component)
export default class Calculator {
  // ...
}

// app.mjs
import { add, multiply, PI } from './math.js';
import Calculator from './calculator.js'; // Default import
import * as math from './math.js';       // Namespace import

console.log(add(2, 3));   // 5
console.log(PI);           // 3.14159

Enter fullscreen mode Exit fullscreen mode

Key Differences

Feature CommonJS ESM
Loading Synchronous Asynchronous
this at top level {} undefined
Can use in browser? No (needs bundler) Yes (natively)
Tree-shakeable? No Yes
Top-level await? No ✅ Yes!
Dynamic imports? require() import()

Dynamic Imports — Code Splitting

// Load only when needed (lazy loading)
async function loadDashboard() {
  const { renderDashboard } = await import('./dashboard.js');
  renderDashboard();
}

// Route-based code splitting (React example)
const Home = lazy(() => import('./pages/Home'));
const Settings = lazy(() => import('./pages/Settings'));

// Conditional imports
if (process.env.NODE_ENV === 'development') {
  const devTools = await import('./dev-tools.js');
  devTools.init();
}

Enter fullscreen mode Exit fullscreen mode

Re-exports (Barrel Files)

// utils/index.js — barrel file
export { formatDate } from './date.js';
export { slugify } from './string.js';
export { debounce, throttle } from './fn.js';

// Now consumers can:
import { formatDate, slugify } from './utils/index.js';
// or just: import { formatDate } from './utils';

Enter fullscreen mode Exit fullscreen mode

Import Maps (Browser)

<script type="importmap">
{
  "imports": {
    "lodash": "https://cdn.skypack.dev/lodash",
    "react": "https://esm.sh/react@18"
  }
}
</script>

<script type="module">
  import _ from 'lodash';          // Works without bundler!
  import React from 'react';
</script>

Enter fullscreen mode Exit fullscreen mode

Package.json Configuration

{
  "name": "my-package",
  "version": "1.0.0",
  "type": "module",              //  Treat all .js files as ESM!

  "exports": {                   //  Control what's accessible externally
    ".": "./dist/index.js",
    "./utils": "./dist/utils.js"
  },

  "imports": {                   //  Internal path aliases (Node.js)
    "#config": "./src/config.js",
    "#utils": "./src/utils/"
  },

  "main": "./dist/index.js",     // For CJS consumers
  "module": "./dist/index.esm.js", // For ESM consumers (bundlers)
  "types": "./dist/index.d.ts"   // TypeScript types
}

Enter fullscreen mode Exit fullscreen mode

Interop (Mixing CJS and ESM)

// Importing CJS into ESM
import pkg from 'commonjs-package';        // Default import works
import { namedExport } from 'cjs-pkg';     // May not work if CJS doesn't export named!

// Importing ESM into CJS
// ❌ You can't require() an ESM-only package!
// Solution: Dynamic import (works in both):
(async () => {
  const esmModule = await import('esm-package');
  console.log(esmModule.default);
})();

Enter fullscreen mode Exit fullscreen mode

Practical Patterns

Singleton Pattern

// db.js — only runs once, cached by module system
let connection = null;

export async function getConnection() {
  if (!connection) {
    connection = await createConnection();
  }
  return connection;
}

// Every file that imports this gets the SAME connection instance

Enter fullscreen mode Exit fullscreen mode

Config Pattern

// config.js
const env = process.env.NODE_ENV || 'development';

export const config = Object.freeze({
  isDev: env === 'development',
  isProd: env === 'production',
  apiBase: env === 'production' ? 'https://api.example.com' : 'http://localhost:3000',
  dbUrl: process.env.DATABASE_URL!,
  port: parseInt(process.env.PORT || '3000'),
});

Enter fullscreen mode Exit fullscreen mode

Type-Only Imports (TypeScript)

// type.ts
export interface User { name: string; age: number; }

// app.ts
import type { User } from './types.js';      // Erased at compile time!
import { someFunc, type Result } from './lib'; // Mixed import

Enter fullscreen mode Exit fullscreen mode


Are you still using CommonJS or fully migrated to ESM?

Follow @armorbreak for more JavaScript content.