liveBook · Manning

Import/export syntax

As explained in The Joy of JavaScript

A JavaScript module feature for making bindings or values available to other modules.

Import/export syntax is the ESM mechanism for sharing selected bindings between JavaScript modules. A module keeps its declarations private by default and exposes an interface with export; import consumes that interface. ESM uses a static module format, allowing build tools to analyze dependencies and optimize bundled code. section 1.4 section 6.4 section 6.4.2

Choose an export shape that matches the module’s responsibility:

  • Use a default export when a module primarily provides one class, function, or other value. section 6.4.2
  • Use named exports when a utility module provides several standalone functions, such as validation operations. section 6.4.2
  • Use re-exports to assemble a public entry point from modules such as Block, Transaction, and Blockchain. section 6.4.2
  • Write explicit module paths for relative, absolute, or remote resources; ESM does not retain Node.js directory-import shortcuts. section 6.4.1

Default and named exports

A class-focused module can expose one primary value: `export default class Transaction { /* ... */ }`. A utility module can expose several operations: `export const checkDifficulty = block => /* ... */` and `export const checkGenesis = block => /* ... */`. These choices make the intended module API visible while keeping supporting declarations private. section 6.4.2

export { default as Block } from './domain/Block.js'
export { default as Transaction } from './domain/Transaction.js'
export { default as Blockchain } from './domain/Blockchain.js'

Shows how re-exported domain modules form a single public API. section 6.4.2

How The Joy of JavaScript covers it

How deep it goes
Defines module privacy, export forms, path specifiers, and static analysis, while deferring the complete set of syntax combinations.
Examples
Uses classes, validation utilities, blockchain domain modules, relative paths, absolute paths, and remote module URLs.
What it assumes
Builds from JavaScript files and module paths, while defining ESM’s special semantics and automatic strict mode.
What you can do after
Apply it via ESM to design reusable module APIs and expose only the code other parts of an application need.
How it connects
Connects ESM with CommonJS, AMD, module paths, dependency management, bundling, modularity, and separation of concerns.

Also explained in

Compare how 5 books explain import/export syntax →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Joy of JavaScript. The section links point to the parts of the book it draws on.