ECMAScript Modules

aka

JAVASCRIPT MODULES

aka

ESM

aka

MJS

by

Troy Rhinehart

ECMAScript Modules

aka

JAVASCRIPT MODULES

aka

ESM

aka

MJS

by

Troy Rhinehart

Browser Support

exports

  • Individual
  • List
  • Re-Exporting

Exports: Individual

// named export
export const a = "a";

// named function
export function b() {}

// named class
export class c {}

// default anon class
export default class {}

Exports: List

// named variable
const a = "a";

// named function
function b() {}

// named class
class c {}

// anon class
const d = class {};

// exported list, with rename
export { a, b, c, d as default };

Exports: Re-exporting

// export everything but default
export * from "./file.js";

// export only default
export { default } from "./file.js";

// export everyting, including default, as named exports
export * as list from "./file.js";

// export named exports
export { a, b, c as default } from "./file.js";

imports

  • Default
  • Named
  • Wildcard
  • Dynamic

Imports: Default

// import default export
import a from "./file.js";

// or named export
import { default as b } from "./file.js";

// or both
import c, { default as d } from "./file.js";

// they all are the same export
console.assert(a === b && b === c && c === d)

Imports: Named

// import single
import { a } from "./file.js";

// import multiple
import { b, c as fileC } from "./file.js";

// IMPORTANT: named exports is NOT a destructure
import d, { e } from "./file.js";
console.assert(d.e !== e);

Imports: Wildcard

// import all exports
import * as a from "./file.js";

// import default, and all exports
import b, * as c from "./file.js";

console.assert(a === c);
console.assert(b === c.default);

Imports: Dynamic

// static import
import * as a from "./file.js";

// dynamic import (Promise)
import("./file.js").then(b => {
  console.assert(a === b);
});

gottchas: top level only

// parsing error
(() => {
  import a from "./file.js";
})();
// parsing error
(() => {
  export default "a";
})();

gottchas: exports are immutable bindings

// example.js
export let value = 1;

export function increase() {
  value++;
}
import { value, increase } from "./example.js"

console.assert(value === 1);

// mutates value binding
increase();

console.assert(value === 2);

// TypeError: Assignment to constant variable
value++;

gottchas: Treeshaking

// example.named.js
export const a = "a";

export const b = "b";
// b is not referenced, can be deleted
import { a } from "./example.named.js"
// example.default.js
export default {
  a: "a",
  b: "b"
}
// b is not referenced, but is included
import all from "./example.default.js"

const { a } = all;

Questions?

ES Modules

By gingur

ES Modules

  • 77