Exporting and Importing

Junior Year, page 2 of 11. A two-minute read.

Let's make a module. Create a file called math-utils.js:

math-utils.js
export const PI = 3.14159;

export function add(a, b) {
  return a + b;
}

export function circleArea(radius) {
  return PI * radius * radius;
}

// not exported, so it's private to this file
function secretHelper() {
  return "You can't see me!";
}

The keyword export in front of a variable or function means "other files are allowed to use this." Anything without export (like secretHelper) stays private to the module.

Now, in another file, you can import what you need:

main.js
import { add, circleArea } from "./math-utils.js";

console.log(add(2, 3));      // 5
console.log(circleArea(10)); // 314.159

The curly braces list exactly which exports you want, and the string after from is the path to the file. The ./ means "in the same folder as this file." (../ means "in the folder above.")

Named exports and default exports

What we just used are called named exports: each export has a name, and you import it by that exact name. A module can have as many named exports as it likes.

A module can also have one default export: the "main thing" the module provides. It's written with export default, and imported without curly braces, using any name you like:

greeter.js
export default function greet(name) {
  return `Welcome, ${name}!`;
}

export const VERSION = "1.0";
main.js
import greet, { VERSION } from "./greeter.js";
import sayHello from "./greeter.js"; // same default export, different name

console.log(greet("Zoe"));      // Welcome, Zoe!
console.log(sayHello("Sam"));   // Welcome, Sam!
console.log(VERSION);           // 1.0

A few more import tricks:

JavaScript
// rename an import to avoid a clash
import { add as addNumbers } from "./math-utils.js";

// import everything as one object
import * as MathUtils from "./math-utils.js";
console.log(MathUtils.add(1, 1));
console.log(MathUtils.PI);
TipNamed or default?

Many teams prefer named exports for almost everything, because the names stay consistent across the whole project (everyone calls add "add") and code editors can auto-import them more easily. Default exports are common for a module's single "main" thing, like a class or a component. Both are fine; just be consistent.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning