JavaScript Modules - Exercise 2

Use export default for the module's primary value or function. A module can have only one default export, although it may also have named exports.

javascript

export default function createUser(name) {
  return { name };
}

Import a default export without curly braces, and choose the local name in the importing file. The chosen name does not need to match the declaration's name.

javascript

import makeUser from './user.js';
const user = makeUser('Ada');

Put the default import first, followed by named imports in braces. One statement can then receive the module's primary value and selected additional exports.

javascript

import Circle, { square, triangle } from './shapes.js';
console.log(Circle(5), square(4), triangle(6, 8));

Use an export-from statement to create a public entry point that forwards selected exports. Consumers can import from that entry module without knowing the internal file layout.

javascript

// index.js
export { formatCurrency } from './currency.js';
export { calculateTax } from './tax.js';

Omit import bindings when the module is needed only for its evaluation side effect, such as registering a listener. The module still runs once, but no exported value is assigned locally.

javascript

import './register-service-worker.js';

Call import() when the module is needed rather than loading it at startup. It returns a Promise for the module namespace, so use await or .then().

javascript

const module = await import('./chart.js');
module.renderChart(data);

Keep implementation details private and export only the functions other modules need.

javascript

const cache = new Map();
function readCache(key) { return cache.get(key); }
export function getUser(key) {
  return readCache(key);
}

A bundler can remove statically analyzable exports that are never imported, reducing production code.

javascript

// utils.js
export function used() {}
export function unused() {}
// main.js
import { used } from './utils.js';
used();

A namespace import collects a module's named exports under one object-like name.

javascript

import * as math from './math.js';
console.log(math.add(2, 3));
console.log(math.subtract(5, 1));

Import a module without bindings when you need its initialization or other side effects to run.

javascript

import './register-custom-elements.js';
// The module runs during application startup.
All sections expanded. Activate the control to collapse all sections.