ILILCode
HomeJavaScriptAdvanced

Modules: split code into files that know their job

Named and default exports, import syntax, and how to keep a codebase navigable.

Lesson 15 of 23 in JavaScript9 min1 exercise

A module is a file with its own scope. Nothing leaks out unless you export it, and nothing comes in unless you import it. That single rule is why modules scale.

math.js
export const PI = 3.14159;

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

export function area(radius) {
  return PI * radius ** 2;
}
main.js
import { add, area } from "./math.js";
import * as math from "./math.js";

add(2, 3);        // 5
math.area(2);     // 12.56636

There is also a default export: export default function greet() {}, imported as import greet from "./greet.js". One default per file, any number of named exports. Named exports are usually kinder to readers — the name is the same everywhere.

Browser modules need type="module"
<script type="module" src="./main.js"></script>

<!-- imports must be relative paths with a file extension -->
<script type="module">
  import { add } from "./math.js";
  console.log(add(1, 2));
</script>

Try it

Two worlds, one screen

main.js
console · output appears here

Exercises

Checked in your browser · hints and solutions included

01

Exercise

Write a reusable slugify helper

Write slugify(title) that turns a title into a URL slug:

  1. 01lowercase it
  2. 02trim the ends
  3. 03replace every run of characters that are not a-z or 0-9 with a single -
  4. 04remove leading and trailing -

slugify("Hello World") → "hello-world".

In a real project this would be export function slugify(title). Here, just declare it.

exercise.js
console · run your code or check the answer