669 words
3 min read

Future-Proofing JavaScript with ESM and CJS Compatibility Techniques

By Docker Captain · CNCF Ambassador · IBM Champion
Cover image for the post 'Future-Proofing JavaScript with ESM and CJS Compatibility Techniques'

JavaScript’s module system is a lot like Git. Powerful, confusing, and still a daily source of pain years after you thought you’d figured it out.

Published an NPM package lately? Then you’ve fought this. You add "type": "module" to your package.json, and half your consumers start screaming. Or you leave it off, and now tree-shaking is dead. There’s no clean default. It’s a mess either way.

So let’s fix it.

This guide is about building dual-compatible JavaScript packages. Packages that work whether someone require()s them or imports them, without blowing up your CI pipeline and without giving up modern tooling.

Why You Should Care (Even as a DevOps Engineer)#

You probably think this is a frontend problem. It isn’t. CLI tools, Dockerized apps, Lambda functions, microservices in Node.js: for all of them, module format matters.

Build tooling wants ESM. Legacy code wants CJS. Your job is to feed both without the whole thing folding in on itself like a badly wired monorepo.

The ESM vs. CJS TL;DR#

I’ll skip the history lesson. Here’s what actually matters in practice:

FormatESMCJS
Syntaximport/exportrequire/module.exports
Node.jsDefault in .mjs or "type": "module"Default in .js or "type": "commonjs"
ProsNative in browsers, tree-shaking, async importsUbiquitous, works everywhere
Consrequire() of ESM needs Node 20.19+ or 22.12+ and no top-level awaitESM can import it, but named exports depend on static analysis

So no, slapping .mjs on everything and praying is not a strategy. Do it properly.

Rule #1: Don’t Use "type": "module" in Shared Packages#

Set "type": "module" in a library’s package.json, and you’ve just locked that library into ESM-only territory.

Now every CJS consumer is stuck doing bundler gymnastics to use it. Bad trade.

Do this instead. Define dual entry points and let the consuming app pick what it wants.

Example: Dual-Compatible package.json#

This is the config I actually ship in real packages. Clean, and it works:

{
"name": "example-library",
"version": "1.0.0",
"description": "Dual ESM and CJS compatible library",
"main": "dist/index.cjs",
"module": "dist/index.mjs",
"exports": {
".": {
"require": "./dist/index.cjs",
"import": "./dist/index.mjs"
}
},
"keywords": ["esm", "cjs", "npm", "compatibility"],
"license": "MIT"
}

Why this works#

  • main: Used by CJS consumers and legacy bundlers
  • module: Used by modern bundlers like Vite, Webpack (for ESM)
  • exports: Official Node.js way to define conditional entry points

✅ This setup lets both require() and import work cleanly without surprises.

Common Mistakes#

  • Mixing CJS and ESM in the same file: Just don’t. Keep them separate.
  • Forgetting .cjs and .mjs extensions: Node cares. A lot.
  • Assuming bundlers will “just handle it”: Spoiler. They won’t.

Build Setup for Both Formats#

Reach for a bundler like rollup or tsup and compile both module types from one source. Here’s a config:

Terminal window
tsup src/index.ts \
--format cjs,esm \
--dts \
--out-dir dist

That gives you dist/index.cjs, dist/index.mjs, and dist/index.d.ts. One build, both formats, no drama.

Docker and DevOps Considerations#

Shipping Node apps in Docker? You should be. And when you do, test both module formats inside the container. I’ve watched far too many CI pipelines pass locally and then fall over the moment node inside Alpine choked on the wrong module format.

Here’s what I do:

  1. Base the image on the current Active LTS line, node:26-alpine as of November 2026, and pin it by digest: FROM node:26-alpine@sha256:<digest>. docker buildx imagetools inspect node:26-alpine prints the digest. Node 18 and 20 are end-of-life. Don’t ship them.

  2. Validate both formats in your CI pipeline:

    Terminal window
    node -e "require('./dist/index.cjs')"
    node --input-type=module -e "import('./dist/index.mjs')"
  3. Lock your build environment with package-lock.json and exact versions.

Consistency is king. In Docker, the small inconsistencies are the ones that kill you.

Real-World Example: CLI Tool Distribution#

We built a small CLI tool that ended up spreading across several dev teams. Some pulled it in with require(). Others imported it as an ESM module in their Vite setups.

We could have picked one and annoyed half of them. We went dual-mode instead. Here’s what worked:

  • Split output with tsup
  • Defined conditional exports
  • Wrote one internal API, wrapped with two interfaces (CJS and ESM)

The result? One package, two module styles, nobody complaining.

Takeaway#

Supporting both ESM and CJS is about more than compatibility. It’s about longevity. The Node.js ecosystem is not flipping to ESM-only overnight, and you want your package to work today, and still work five years from now.

So build smart. Support both. Don’t make your users fight the module loader.


Vladimir Mikhalev

Docker CaptainCNCF AmbassadorIBM Champion

The Verdict — production-tested analysis on YouTube.

The Verdict

Inconvenient truths about shipping in the AI era

Container security, platform engineering, and the agentic shift — tested in production, argued without the hype. The verdict reaches your inbox the moment there's one worth sending.

Related Posts

Same category
  1. 1
    Docker Hardened Images Migration: A Healthy Database That Kept Nothing
    DevOps & Cloud · Moving a Compose stack to Docker Hardened Images changes user IDs, paths and tools. On the old mount path, PostgreSQL stayed healthy and kept nothing.
  2. 2
    EKS Validation on a Real AWS Account: Seven Failures No Mock Saw
    DevOps & Cloud · Proving an EKS platform on a real AWS account: twenty cents a run by estimate, about fifty on the bill, and seven failures no mocked test or kind saw.
  3. 3
    A Partial Read Is Not a Smaller Fleet: A GitHub API Rate Limit and the Numbers That Lied for an Hour
    DevOps & Cloud · A partial read published as the whole. For an hour the profile said 24 restore scripts across 15 repositories, and the fleet had 73 across 48. Three guards now.
  4. 4
    Restore Drills on a Clean Machine — Measured RTO for 47 Stacks, 19 Seconds to 7 Minutes
    DevOps & Cloud · Restore drills that measure RTO on a machine that never ran the stack, 47 templates weekly. Every same-host restore passed. The first clean one answered 500.

Random Posts

Random
  1. 1
    Amazon's Project Dawn Cut 16,000 Jobs. What It Means for Community Programs.
    Opinion & Culture · Project Dawn cut about 16,000 Amazon corporate jobs in January 2026, about 30,000 with October's round. The signal for community programs: prove production value, not engagement metrics.
  2. 2
    Install Keycloak Using Docker Compose
    Self-Hosting · Learn how to install Keycloak using Docker Compose with Traefik and Let's Encrypt. Step-by-step setup for secure identity and access management on your server.
  3. 3
    The Intake Gate Your CISO Is Missing: 300 Million AI Chat Messages Left Public by a Test-Mode Rule
    AI & MLOps · One researcher found 103 of 200 Firebase iOS apps open the same way. Inside the 300M-message breach and a 3-layer intake protocol to stop Agent Sprawl.
  4. 4
    Install PuppetDB on Ubuntu Server
    DevOps & Cloud · Learn how to install and configure PuppetDB on Ubuntu Server with PostgreSQL. Complete setup guide for integrating with Puppet for infrastructure data.
Future-Proofing JavaScript with ESM and CJS Compatibility Techniques
https://heyvaldemar.com/future-proofing-javascript-with-esm-and-cjs-compatibility-techniques/
Author
Vladimir Mikhalev
Published
2024-05-08
Updated
2026-06-16
License
CC BY-NC-SA 4.0