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 of those keywords is a module, and the top level of a module has its own scope instead of sharing the global one.
// ---- math.js, written as an ES module ----
// export function add(a, b) { return 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)); // 6
There are three ways to import. A named import uses braces and pulls in one or more specific exports. A default import pulls in the default export and gives it any local name you like. A namespace import uses the star syntax and pulls everything into a single object, which is useful when you want to forward a whole module.
Exports work in the same way but in reverse. You can export a declaration directly by putting export in front of it. You can export a list of existing names at the bottom of the file. Or you can export something as the default, which is the single main export of the module.
Two rules make the whole system work. A module is evaluated once, and its exports are live views, so when a value changes, the importer sees the new value. And imports are hoisted, so you can use an imported name before the import statement appears in the file. That is different from the old CommonJS behaviour, where the require call has to run first.