liveBook · Manning

Default export

As explained in Secrets of the JavaScript Ninja, Second Edition

The binding or value designated as a module's default export, which can be imported under a chosen local name.

A default export designates one binding to represent a module, rather than requiring consumers to choose among several named exports. It is often useful when a module centers on a single class. A module can also provide named exports alongside its default. section 11.2.1

Listing 11.9. A default export from Ninja.js
export default class Ninja {                           #A
  constructor(name){
    this.name = name;
  }
}

export function compareNinjas(ninja1, ninja2){         #B
  return ninja1.name === ninja2.name;
}

A class can be declared as the default export while a comparison function remains a named export. section 11.2.1

Listing 11.10. Importing a default export
import ImportedNinja from "Ninja.js";                                   #A
import {compareNinjas} from "Ninja.js";                                 #B

const ninja1 = new ImportedNinja("Yoshi");                              #C
const ninja2 = new ImportedNinja("Hattori");                            #C
                                                                        #C
assert(ninja1 !== undefined                                             #C
    && ninja2 !== undefined, "We can create a couple of Ninjas");       #C

assert(!compareNinjas(ninja1, ninja2),                                  #D
      "We can compare ninjas");                                         #D

Import the default class without braces and give it a local name of your choice; import named exports with braces. section 11.2.1

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Explains default-export syntax, arbitrary import naming, and coexistence with named exports through a worked class example.
Examples
Uses a Ninja class as the default export and imports it alongside a named function for comparing instances.
What you can do after
Apply it via ES6 import syntax to bind the default class locally, instantiate it, and combine it with a named import.
How it connects
Connects default exports to ES6 modules, named exports, and import syntax.

Also explained in

Compare how 3 books explain default export →

Related concepts

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