2.6 export import reactions

Modern JavaScript lets you split your code into several files and explicitly declare what each file exposes and what each file consumes. The two keywords are export and import, and together they form the ES6 module system. The idea is that each .js file becomes a self-contained module that announces its dependencies, instead of relying on the loading order of <script> tags in HTML.

Default and named exports

There are two flavours of exports. A file can have a single export default, typically the main thing it provides, and any number of named exports for additional helpers and constants. The import side mirrors that: import Person from "./person.js" grabs the default export (the name on the left is free to choose), while import { clean, baseData } from "./utility.js" targets named exports by their exact names inside braces.

// person.js
const person = { name: "Matthieu", age: 30 };
export default person;

// utility.js
export const clean = () => { /* ... */ };
export const baseData = 10;

// app.js
import Person from "./person.js";
import { clean, baseData } from "./utility.js";
import { baseData as bd } from "./utility.js";   // alias
import * as bundled from "./utility.js";          // import everything as object

The as keyword lets you give a local alias to a named import, which is handy when two modules export the same name. The * as name form imports every export of a file as properties of a single object, which can be convenient when you grab a lot of things from the same module. Not all browsers natively support these features yet, so React projects use a build tool (Babel, webpack) to translate the next-generation JavaScript into something every browser can run.