liveBook · Manning

Import statement

As explained in Secrets of the JavaScript Ninja, Second Edition

JavaScript module syntax for bringing exported bindings from another module into the current module's scope.

An import statement brings identifiers explicitly exported by another ES6 module into your module. Unexported identifiers stay private, so importing a module does not expose everything defined inside it. section 11.2 section 11.2.1

Choose an import form to match what you need:

  • Import named exports directly, or rename one with `as`. section 11.2.1
  • Import all named exports under a namespace, then access them through properties. section 11.2.1
  • Import a module’s default export; combine it with named imports when needed. section 11.2.1
Listing 11.7. Importing from the Ninja.js module
import { message, sayHiToNinja} from "Ninja.js";               #A

assert(message === "Hello",                                    #B
      "We can access the imported variable");                  #B
assert(sayHiToNinja() === "Hello Yoshi",                       #B
      "We can say hi to Yoshi from outside the module");       #B

assert(typeof ninja === "undefined",                           #C
      "But we cannot access Yoshi directly");                  #C

The example imports `message` and `sayHiToNinja` from `Ninja.js`; it accesses both, but not the unexported `ninja` identifier. section 11.2.1

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Explains named, namespace, default, and aliased imports, and shows that unexported identifiers remain inaccessible.
Examples
Uses `Ninja.js` examples to import named exports, a namespace, a default class, and an aliased function.
What you can do after
Apply named, namespace, default, and aliased imports to access exported module identifiers.
How it connects
Connects imports with exports, ES6 modules, CommonJS, and AMD.

Also explained in

Compare how 13 books explain import statement →

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.