ECMAScript Modules (ESM)

Dec 01, 2020javascriptjs-modules

ESM is the ECMAScript standard for working with modules, this standardization process completed with ES6 and browsers started implementing this standard trying to keep everything well aligned.

The goal for ESM was to create a format that both users of CommonJS and of AMD are happy with: Similarly to CommonJS, they have a compact syntax, a preference for single exports and support for cyclic dependencies. Similarly to AMD, they have direct support for asynchronous loading and configurable module loading.

Within a module, you can use the export keyword to export just about anything, you can export a const, a function, or any other variable binding or declaration.

// hello.js
export const apiKey = 'random-key-her'
export const doSomething = () => {
  console.log('hello there')
}
export default doSomething

You can then use the import keyword to import the module from another module.

// main.js
import doSomething, {apiKey} from './hello'

console.log(apiKey)
doSomething()

The newest part of the JavaScript modules functionality to be available in browsers is dynamic module loading. This allows you to dynamically load modules only when they are needed, rather than having to load everything up front. This has some obvious performance advantages.

import('./awesome-module.js').then((module) => {
  // Do something with the module.
})

ES modules allow static analysis that helps with optimizations like tree-shaking and scope-hoisting, and provide advanced features like circular references and live bindings.