How do you import and export things in a JavaScript module?
An ES module uses the export keyword to publish values and the import keyword to bring them in. A file that contains either keyword is a module, and its top level has its own scope rather than sharing the global one.
// ---- math.js, written as an ES module ----
// export const add = (a, b) => a + b;
// export default function multiply(a, b) { return a * b; }
//
// ---- app.js ----
// import multiply, { add } from "./math.js";
function add(a, b) {
return a + b;
}
function multiply(a, b) {
return a * b;
}
// The same module written with CommonJS, which is what runs as a plain script:
const mathModule = { add, default: multiply };
console.log(mathModule.add(2, 3)); // 5
console.log(mathModule.default(2, 3)); // 6There are three import forms. A named import uses braces and pulls one or more specific exports. A default import pulls the default export and gives it any local name you like. And a namespace import uses the star syntax to pull everything into a single object, which is useful when you want to forward a whole module.
Exports work the same way in reverse. You can export a declaration directly by putting export in front of it, you can export a list of existing bindings at the bottom of the file, or you can export something as default, which is the single main export of the module.
Two rules make the system work. A module is evaluated once and its exports are live views, so if a value changes, an importer sees the new value. And imports are hoisted, so you can use an imported binding before the import statement appears in the file, which is a difference from the CommonJS behaviour where the require call has to run first.