Splitting a program into files
Putting a whole program in one file works for a few dozen lines. Beyond that it becomes hard to read, hard to test, and easy to break. Modules let you split code into separate files, each focused on one job, and pull pieces from one file into another when needed. It's like organising a kitchen into labelled drawers: utensils in one, spices in another, so you can find what you want quickly.
Each module also gets its own scope. A variable defined inside one module doesn't leak into another unless you explicitly export or import it, which prevents accidental name clashes.
Exporting and importing in JavaScript
Here are two files. The first exports a function; the second imports and uses it:
// math-utils.js
export function square(n) {
return n * n;
}
// app.js
import { square } from "./math-utils.js";
console.log(square(7)); // 49
Python works the same way with less ceremony: any .py file is a module, and from math_utils import square brings in the function.
Module vs package
A package groups modules together so they can be published and installed as one unit. If a module is a single chapter, a package is the bound book. You write modules all the time inside your own project; you only create a package when you want to share code beyond it.
Different languages use slightly different terms. Java organises classes into "packages" at the source level and has had a separate "module" system since Java 9. Go calls a versioned collection of packages a "module." When reading documentation, check how that language defines the words.
A module can export any function, class, or value you want other files to reach.
Learn more
Last updated