JavaScript Modules - Exercise 2
Use export default. A module can have only one default export.
export default function createUser(name) {
return { name };
}Import it without curly braces. The local name can be chosen by the importer.
import makeUser from './user.js';
const user = makeUser('Ada');Put the default import first, followed by named imports in braces.
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.
// index.js
export { formatCurrency } from './currency.js';
export { calculateTax } from './tax.js';Omit the import bindings when the module runs setup code on evaluation.
import './register-service-worker.js';Call import() when the module is needed. It returns a Promise for the module namespace.
const module = await import('./chart.js');
module.renderChart(data);Keep implementation details private and export only the functions other modules need.
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.
// utils.js
export function used() {}
export function unused() {}
// main.js
import { used } from './utils.js';
used();