LESSON 27 · BEGINNER4 min read

ES Modules: Import & Export

Split code into focused files, share only what is needed, and load optional features on demand.

ES2024 / Node.js 20+Free to readModule 6 of 19
YOUR NEXT SMALL WINS

By the end, you’ll be able to…

  • Explain module scope and how the browser evaluates a module graph.
  • Write named and default exports and import them with aliases.
  • Describe live bindings, re-exports, and when to use dynamic import.
  • Recognise the file, MIME, and path rules that differ between browsers and Node.js.

01Why modules exist

Before modules, a browser page loaded scripts into one shared global scope. A variable declared in one file could collide with a variable in another, and load order became part of the program's meaning. ES modules give each file its own scope. Top-level declarations stay private unless exported, and importing a file does not leak its names into the page. The browser also executes modules in strict mode and defers them until the document has been parsed.

A module is still a normal JavaScript file. What changes is how it is loaded and how its bindings are shared. The module graph starts from one entry file, follows its import statements, and evaluates dependencies before the importer. Each module is evaluated once, no matter how many other modules import it. That single evaluation makes a module a good place for shared configuration or a single application store.

app.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

02Named exports and imports

A named export attaches a name to a declaration. You can export a function, a constant, or a class at the point of declaration, or collect names in an export list. The importer must use the same name unless it aliases it with as. Named exports are explicit: an editor can show where each value is used, and a reader can see exactly what a module offers.

A module can also have one default export. That is useful when the module's main purpose is a single value, such as a component or a class. Import a default without braces and choose any local name. Mixing default and named exports is legal, but a module with only named exports is often easier to refactor. Choose one convention for a project and keep it predictable.

format.js and app.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

03Live bindings and re-exports

Imported bindings are live views of the exporter's variables, not copies. If the exporting module changes a count, importers see the new value the next time they read it. The binding is read-only from the importer's side: assigning to it is an error. This behaviour makes a shared counter or configuration value observable without a subscription mechanism, but it is not a replacement for a state management design.

A barrel file re-exports selected names so consumers can import from one path. Use export { name } from './name.js' or export * from './name.js' for a namespace-like surface. Re-exports are convenient at a package boundary, but deep barrels can hide dependencies and create circular imports. Prefer direct imports inside an application, and reserve a barrel for the public entry point of a folder or package.

counter.js and app.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

04Dynamic import and environment differences

A static import is resolved before the module runs, which is good for the main dependencies. When a feature is optional or expensive, import() loads a module on demand and returns a promise. The browser can fetch it only when needed, and you can catch a failed network request. Dynamic import is common for heavy editors, charts, or locale files that many visitors never use.

Browsers require a script tag with type set to module, and they expect modules to be served with a JavaScript MIME type. Relative paths need the .js extension, and file:// pages often block module loading, so use a local server. Node.js uses the same syntax but decides module type from package.json or the .mjs extension. For larger projects, group files by feature and keep shared utilities in a clearly named common folder; clear boundaries beat deep nesting. These environment rules explain many cannot-use-import errors.

lazy.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
LET IT CLICK

The ideas worth keeping.

  • Each ES module has its own scope and is evaluated once as part of the module graph.
  • Use named exports for explicit APIs, a default for a module's single main value, and aliases to keep local names readable.
  • Dynamic import defers optional code, while browser and Node.js environments impose their own path and loading rules.
TURN UNDERSTANDING INTO SOMETHING YOU CAN DO

Make it yours.

Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.

01

Exercise 1: Split formatting helpers

Create format.js with a named export formatPrice, a named export formatDate, and a default export for the currency code. Then write app.js that imports the default as currencyCode, imports formatPrice with the alias price, and logs a formatted result.

your_turn_1.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.jsJavaScript
// format.jsexport const formatPrice = (cents) => "$" + (cents / 100).toFixed(2);export const formatDate = (date) => date.toISOString().slice(0, 10);export default "USD";// app.jsimport currencyCode, { formatPrice as price } from "./format.js";console.log(currencyCode, price(499));

The default export is imported without braces and can be renamed freely. The named export uses an alias, so the local name price is clear at the call site while the module keeps its own name.

02

Exercise 2: Lazy-load a report

Write an async function showReport() that dynamically imports './report.js', calls its exported renderReport function with the selector '#report', and returns true. If the import or render call throws, log a warning and return false.

your_turn_2.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.jsJavaScript
async function showReport() {  try {    const module = await import("./report.js");    module.renderReport("#report");    return true;  } catch (error) {    console.warn("Report unavailable:", error);    return false;  }}

Dynamic import returns a promise, so the function must be async. Awaiting it gives the module namespace object, whose exported renderReport can be called. The catch covers both a failed fetch and a render error.

A SMALL QUESTION. A USEFUL NEXT STEP.

What stayed with you?

Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.

A LITTLE ACTIVE RECALL0 / 3 answered
01How must a named export be imported?
02What does it mean that an imported binding is live?
03Why might a browser fail to load modules from a file:// URL?
⚡CODING CHALLENGE
🔒Required to Mark Lesson Complete

Exercise 1: Split formatting helpers

Create format.js with a named export formatPrice, a named export formatDate, and a default export for the currency code. Then write app.js that imports the default as currencyCode, imports formatPrice with the alias price, and logs a formatted result.

main.jsJavaScript
Ctrl + ↵
Execution Console
Click "Run & Verify" (or press Ctrl + Enter) to test your code against the challenge.

Keep exploring.

The official references behind this lesson, when you want a second angle or the full details.

One lesson closer.

Reading is a start. Trying it yourself makes the connection.

Solve the hands-on coding challenge in the knowledge section to verify your code and unlock lesson completion.