ES Modules: import & export

Break your codebase into manageable files. Learn the syntax for named and default exports to share code across your application.

JavaScript5 min readConcept 46 of 62

The Module System

Historically, all JavaScript was dumped into a single massive file or loaded via multiple <script> tags, causing global variables to collide and overwrite each other.

**ES Modules (ESM)** is the modern standard for organizing JavaScript. It allows you to break your code into separate files (modules) that have their own private scope. You explicitly declare what to share (export) and what to bring in (import).

Named vs Default

There are two ways to export data from a module:

1. **Named Exports:** Use when exporting multiple things. You must use the exact same name when importing, wrapped in curly braces: import { sum, multiply } from './math.js';

2. **Default Exports:** Use when a file exports exactly one primary thing (like a single React component). You can name it whatever you want when importing, without curly braces: import MathLibrary from './math.js';

Writing Modules

To create a named export, put the keyword in front of the declaration:

javascript export const PI = 3.14; export function add(a, b) { return a + b; }

To create a default export, use export default:

javascript export default function calculateArea(r) { return PI * r * r; }

Visualizing the Wiring

Study the architecture diagram below. It illustrates the exact syntax required to wire an exported variable from one file into an imported variable in another.

The Module Bridge

// app.jsimport sum, { PI } from './math.js';
// Using the imported modulesconsole.log(PI); // 3.14
console.log(sum(2, 2)); // 4
math.jsExporter
export const PI = 3.14;
NAMED
export default function sum(a, b) {...}
DEFAULT
app.jsImporter
importsum, {PI}from'./math.js';

Named exports strictly require { curly braces }. Defaults do not.

iA single file can export many named variables, but can only have one default export. Notice how the syntax changes based on which one you are importing!

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1Which syntax correctly imports a Named Export from 'utils.js'?
  2. 2Can a single JavaScript file have multiple Default exports?
  3. 3What was the main problem with loading multiple `<script>` tags before ES Modules existed?

Remember this

  • ES Modules (ESM) give every file its own private scope.
  • Use **Named Exports** (export const x) for multiple items, and import them with curly braces (import { x }).
  • Use **Default Exports** (export default x) for a single main item, and import without curly braces.
  • Named imports must use the exact name, while Default imports can be named anything by the importer.
  • Use the as keyword to rename a Named import to prevent naming collisions.

Done with this concept?

Mark it complete to track your progress. No login needed.