Skip to main content
Albero Academy

ES Modules & Tooling

Split code across files with import/export, understand named vs default exports, and see how npm and bundlers fit together.

Chapter 12JavaScript15 min readBeginner friendly
  • #JavaScript
  • #Modules
  • #npm

Real apps are many files, not one. ES modules are the standard way to split JavaScript into files that share code with import and export. Understanding them — plus how npm and bundlers fit in — is the bridge from scripts to real projects (and to the React and Node courses).

Why modules?

Modules give each file its own scope (no more accidental globals), make dependencies explicit, and let you reuse code. In the browser, load a module script with <script type="module" src="app.js">; in Node, set "type": "module" in package.json.

Named & default exports

two kinds of export
// utils.js
export const PI = 3.14159; // named export
export function area(r) { return PI * r * r; }
export default function greet(name) { // ONE default export per file
return `Hi ${name}`;
}

Importing

matching imports
// Named imports use braces and must match the export name
import { PI, area } from "./utils.js";
// Default import — pick any name
import greet from "./utils.js";
// Rename, and import everything as a namespace
import { area as circleArea } from "./utils.js";
import * as utils from "./utils.js"; // utils.PI, utils.area

npm & packages

npm installs third-party modules from the registry. Import them by name (no path):

terminal
npm init -y # create package.json
npm install date-fns # add a dependency
importing a package
import { format } from "date-fns";
format(new Date(), "dd MMM yyyy");

Bundlers

Browsers can load modules directly, but production apps use a bundler (Vite, esbuild, webpack) to combine files, strip dead code, minify, and transform modern syntax for older browsers. Vite — which the React course used — gives you a dev server with instant hot-reload and a one-command production build. You rarely configure it; it just works.

Practice

Split a small program into a math.js (named exports) and an app.js that imports them. Add one default export and import it too. Then npm install a small package and use it.

Key takeaways

  1. 01ES modules split code across files with import/export; each file has its own scope.
  2. 02Named exports (braces, must match the name) vs one default export per file (any import name).
  3. 03Prefer named exports for explicitness and tooling; default for a file's single main thing.
  4. 04npm installs packages from the registry; import them by name.
  5. 05Bundlers (Vite/esbuild/webpack) combine, minify and transpile for production.