Skip to content

Instantly share code, notes, and snippets.

@antosan
Created August 28, 2021 07:46
Show Gist options
  • Select an option

  • Save antosan/cd4a9a2477f80300c34b9060d91205bb to your computer and use it in GitHub Desktop.

Select an option

Save antosan/cd4a9a2477f80300c34b9060d91205bb to your computer and use it in GitHub Desktop.
ECMAScript Modules (ESM)

ECMAScript Modules (ESM)

  • You should write modular JavaScript code.
  • A modular application is composed of separate independent, interchangeable pieces of functionality stored in modules.
  • A module is just a single JavaScript file.

Before 2015

  • JS had no built-in support for modules (no import/export).
  • Community-developed module systems were available, but they were not standardized.

CommonJS Modules (CJS)

  • Popularized by Node.js.
  • Main use: server. Has to be transpiled and bundled to work in the browser.
  • Synchronous loading.

Asynchronous Module Definition (AMD)

  • Popularized by RequireJS.
  • Main use: browsers.
  • Asynchronous loading.
  • The syntax is less intuitive than CommonJS.

Universal Module Definition (UMD)

  • This is a pattern used to configure several module systems.
  • Capable of working everywhere - client and server.
  • Offers compatibility between AMD and CommonJS.
  • Uses AMD as base with special functionality added to handle CommonJS compatibility.
  • The syntax looks ugly.

ECMAScript Modules (ESM)

  • Introduced in 2015 as a standardized format for modules.
  • Works both in the browser and in Node.js.
  • Has CommonJS-like simple syntax and AMD-like asynchronous loading.

Two approaches to ESM

Explicit ESM

  • Filename .mjs and .cjs extensions.

Implicit ESM

  • Add some metadata to your package.json file.
  • "type": "module" (or "type": "commonjs") determines whether files ending in .js, are treated as ES modules or CommonJS modules.

LINKS

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment