repo

esmodule.com

What are ES modules?

Introduced in the ES6 specification, the ECMAScript modules (ES modules or ESM) format is the standardized format for packaging and organizing JavaScript code. It provides a native way to import and export code across files and packages.

ES modules enable better code organization, dependency management, and enable tools to perform static analysis for optimizations like tree-shaking. Since its official addition to the JavaScript specification, ES modules are now widely adaopted in modern browsers and other runtime environments, making it the universal standard for modularizing JavScript code.

See an example Migrate a project

How it looks

CommonJS

Node.js only, and never part of the language.

math.cjs
function add(a, b) {
	return a + b;
}

module.exports = { add };
app.cjs
const { add } = require('./math.cjs');

console.log(add(1, 2));

ES modules

The same code, in every runtime and bundler.

math.js
export function add(a, b) {
	return a + b;
}
app.js
import { add } from './math.js';

console.log(add(1, 2));

Frameworks

Whether the frameworks you already use publish ES modules on npm.

  • Next.js next CJS only Next.js is CommonJS only.
  • Nuxt nuxt ESM only Nuxt publishes ES modules.
  • Astro astro ESM only Astro publishes ES modules.
  • SvelteKit @sveltejs/kit ESM only SvelteKit publishes ES modules.
  • React Router react-router ESM only React Router publishes ES modules.
  • SolidStart @solidjs/start ESM only SolidStart publishes ES modules.