liveBook · Manning

Entry point

As explained in Secrets of the JavaScript Ninja, Third Edition

A package entry point is a file path that a package exposes as the target of an import specifier.

What file runs when you import a package by name? An entry point is the file path a package exposes for an import specifier. ECMAScript leaves specifier resolution to the runtime. In Node.js, a bare specifier such as "entry-point-example" is treated as a package name; Node searches node_modules, then reads the package’s package.json to find the target. section 13.1.2

Listing 13.9 Defining entry points for a package
{
  "name": "entry-point-example",
  "private": true,
  "type": "module", #A
  "exports": { #B
    ".": "./lib/index.js", #B
    "./ninjas/*": "./lib/ninjas/*.js" #B
  } #B
}

The exports field maps the package root (".") to ./lib/index.js and matching ./ninjas/* subpaths to files under ./lib/ninjas/. The type field makes .js files in this package ESM modules. section 13.1.2

Listing 13.12 Importing from a package
import { lazyGetRandomTurtle } from "entry-point-example"; #A
import { getRandomTurtle } from "entry-point-example/ninjas/turtles"; #B

console.log(getRandomTurtle());
console.log(await lazyGetRandomTurtle());

The first import uses the root entry point; the second uses a subpath entry point. Neither import names the underlying lib file. section 13.1.2

The exports field is the modern way to declare these mappings; older packages may use main. When an import resolves unexpectedly, inspect the package.json installed in node_modules: it can differ from the source repository’s version. Browsers use a different approach—import maps can map bare specifiers to URLs. section 13.1.2

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Works through root and wildcard subpath mappings, but defers the node_modules search algorithm.
Examples
Uses a package manifest and imports from both a package root and a subpath.
What it assumes
Assumes familiarity with import statements while defining bare specifiers and explaining package.json entry-point mappings.
What you can do after
Operate/configure it by declaring exports mappings and checking installed package metadata when imports fail.
How it connects
Connects bare specifiers, ECMAScript modules, package.json exports, node_modules resolution, and browser import maps.

Also explained in

Compare how 14 books explain entry point →

Related concepts

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