Lesson 18 of 199:27 video

JavaScript build tools

The tools around the language, on one small checkout page: npm scripts that name a project's commands, a test with Node's own test runner, a linter and a formatter, TypeScript's type checker, and a bundler (Vite) that follows every import and writes the one small file the browser gets, with tree shaking, minifying and source maps on the way.

In this lesson

  1. 0:00 Intro
  2. 0:57 What a tool is
  3. 1:41 npm scripts
  4. 2:33 Tests
  5. 3:22 Linters and formatters
  6. 4:03 TypeScript
  7. 4:55 Types are erased
  8. 5:31 The bundler
  9. 6:15 Smaller on the way
  10. 7:01 The dev server
  11. 7:26 One command
  12. 8:03 Back to the one line
  13. 8:49 In one line
  14. 9:05 Next time

Open the developer tools on a small checkout page and look at the JavaScript it sent your browser. It’s a single line, 20,294 characters long, with names one or two letters each. Nobody typed that. What the developer wrote was two short files, 22 lines in all, with names you can read. Most large websites show the same gap. So what happens to code between the editor and the browser?

By the end of this lesson you’ll know how a project gives each of its commands a name with npm scripts, which tools check your code before it runs (tests, a linter, and TypeScript), and what the bundler does on the way to the browser, including why it wrote that long line.

The project

Everything below happens in one folder. To follow along you need Node, which comes with npm. Make a folder called checkout and save this in it as package.json:

{
  "name": "checkout",
  "private": true,
  "type": "module"
}

The page itself is index.html, with one script tag in its body:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Checkout</title>
  </head>
  <body>
    <script type="module" src="/src/main.js"></script>
  </body>
</html>

In a src folder, cart.js holds the page’s arithmetic:

export function orderTotal(price, shipping) {
  return price + shipping;
}

export function withTax(total, rate) {
  return total * (1 + rate);
}

And main.js builds the page: a price field, a total, and the day an order arrives. The day comes from date-fns, a package for working with dates:

import { addDays, format } from "date-fns";
import { orderTotal } from "./cart.js";

const price = document.createElement("input");
const total = document.createElement("output");
const arrives = document.createElement("p");
document.body.append("Price: $", price, " Total: ", total, arrives);

const shipping = 5;

price.addEventListener("input", () => {
  total.value = "$" + orderTotal(price.value, 5);
});

arrives.textContent = "Arrives " + format(addDays(new Date(), 3), "EEEE");

Two things in it are wrong. Leave them for now: the tools will find both. Install the one package the page uses:

npm install date-fns

Last, save a file called .gitignore with two lines, node_modules and dist. Some tools read it to learn which folders aren’t yours. Without it, the linter later on would check thousands of other people’s files.

What a tool is

To a browser, your file is a program to run. To a tool, it’s text to read. Each tool in this lesson is a program of its own, and it does one of two things with that text: some read your code and report what they find, and the others read it and write new code.

You install tools from npm like any package, with one flag added:

npm install --save-dev vite

The flag lists the tool in package.json under devDependencies: packages you need while you work on the project, and that visitors never download. date-fns went under dependencies, because the page runs it. npm also makes a node_modules folder and puts the packages in it. With all the tools in this lesson installed, it holds 24 packages and over 100 MB, for a page of 22 lines. None of them changes the language the browser runs. It’s still JavaScript, with a few programs standing around it.

npm scripts

Each tool is started by a command, and commands are easy to forget. So package.json has a section for them, called scripts. Every entry is a name and the command it stands for. Add two:

{
  "name": "checkout",
  "private": true,
  "type": "module",
  "scripts": {
    "dev": "vite",
    "test": "node --test"
  },
  "dependencies": {
    "date-fns": "^4.4.0"
  },
  "devDependencies": {
    "vite": "^8.3.8"
  }
}

Your version numbers may be newer than these. Type npm run and a name, and npm runs that command:

npm run dev

Vite prints ready and an address, http://localhost:5173/. Stop it with Ctrl+C. Now try typing the tool’s name by itself, vite, and the terminal answers command not found. A script runs it because npm knows where the project’s tools are installed: while a script runs, npm puts node_modules/.bin on the list of folders searched for commands.

The second thing scripts buy you is that the names travel with the project. Someone who downloads it, without its node_modules folder, types npm install to fetch every package package.json lists, and then the same short names you do: dev, test, build. A few names are common enough that npm lets you skip the word run: npm test is one, and npm start, npm stop and npm restart are the others. For a one-off, npx and a tool’s name runs that tool without a script:

npx vite --version

A test

The first checker is one you write yourself. A test is a few lines of code that call your code and compare its answer with the one you expect. Save this as src/cart.test.js:

import { test } from "node:test";
import assert from "node:assert/strict";
import { orderTotal } from "./cart.js";

test("a $100 order with $5 shipping costs $105", () => {
  assert.equal(orderTotal(100, 5), 105);
});

Node has a test runner built in. Run with the flag --test, it looks through the project for files whose names end in .test.js (among other patterns) and runs every test in them. That’s the test script:

npm test

It prints ✔ a $100 order with $5 shipping costs $105, then a summary with pass 1 and fail 0. Now break the function on purpose: in cart.js, make the body return price; so it forgets the shipping, and run npm test again. This time the line starts with ✖, and further down the runner prints what it got and what it wanted:

  AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:

  100 !== 105

Nobody had to open the page to see that. Put the shipping back, and from now on this function can’t break quietly. Jest and Vitest are test runners too, with more built in. Tests never reach the browser: nothing the page imports leads to them.

A linter and a formatter

The second checker doesn’t run your code at all. It reads it. A linter carries a long list of patterns that usually mean a mistake, and it flags every one it finds. The best-known linter is ESLint. This lesson uses Oxlint, a newer one that needs no setup:

npm install --save-dev oxlint
npx oxlint

It finds one thing:

src/main.js:9:7: warning eslint(no-unused-vars): Variable 'shipping' is declared but never used. Unused variables should start with a '_'. help: Consider removing this declaration.

The rule’s name is ESLint’s: Oxlint borrows ESLint’s rules and their names. And the warning is right. Three lines further down, the 5 is typed in by hand where the variable should be. Change that call to orderTotal(price.value, shipping) and run npx oxlint again: it finds nothing.

A formatter is the linter’s cousin. It isn’t looking for mistakes. It rewrites the layout, meaning the spaces, the line breaks and the quotes, the same way in every file, so a team never argues about style. The best-known one is Prettier. To watch it work, make cart.js untidy on purpose:

export function orderTotal(price,shipping){ return price+shipping }

export function withTax(total,rate) {
      return total*(1+rate);
}

Then install Prettier, ask it to check every file, and then to fix them:

npm install --save-dev prettier
npx prettier --check .
npx prettier --write .

The check names src/cart.js under [warn]. The second command prints each file it looked at and leaves cart.js exactly as it was at the start of this lesson. Not one token changed, only the layout.

TypeScript

Back to that passing test. Run npm run dev, open http://localhost:5173/, and type 100 into the price field. The total reads $1005. The test passed and the page is wrong.

A field’s value is always a string, and a string plus a number joins the two together:

import { orderTotal } from "./src/cart.js";

console.log(orderTotal("100", 5)); // 1005
console.log(orderTotal(100, 5)); // 105

(Save those three lines as try.js in the project’s folder and run node try.js to see it, then delete the file.) The test never tried a string. A test checks the cases you thought of. TypeScript checks the ones you didn’t.

TypeScript adds one thing to JavaScript: after a name, you can write the type you expect. Install it with the types that describe Node’s own modules, which the test file imports:

npm install --save-dev typescript @types/node

Rename the three files in src from .js to .ts (main.ts, cart.ts and cart.test.ts), and change three paths to match: ./cart.js becomes ./cart.ts in main.ts and cart.test.ts, and the script tag in index.html asks for /src/main.ts. Then give cart.ts its types:

export function orderTotal(price: number, shipping: number): number {
  return price + shipping;
}

export function withTax(total: number, rate: number): number {
  return total * (1 + rate);
}

The checker’s settings live in tsconfig.json. This one says: only check, don’t write files; let imports end in .ts; and load Node’s types:

{ "compilerOptions": { "noEmit": true, "allowImportingTsExtensions": true, "types": ["node"] } }

The checker is a command called tsc. It reads every file and follows every call, without running a line:

npx tsc

It stops on one call, the page’s:

src/main.ts:12:34 - error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

12   total.value = "$" + orderTotal(price.value, shipping);
                                    ~~~~~~~~~~~


Found 1 error in src/main.ts:12

The test passes numbers, so its call is fine. The page passes price.value, a string. Wrap the value in Number in main.ts:

price.addEventListener("input", () => {
  total.value = "$" + orderTotal(Number(price.value), shipping);
});

Run npx tsc again, and it prints nothing. On the page, 100 now gives $105.

Types are erased

No browser runs TypeScript. Hand a browser cart.ts as JavaScript and it stops at the first colon:

Uncaught SyntaxError: Unexpected token ':'

So before the code runs anywhere, the types come out, and that’s all it takes. Delete every annotation from cart.ts and what’s left is plain JavaScript, the code you’d have written without them. Types exist while you write, and they’re gone when the program runs. Node does this itself: npm test still passes, now running cart.test.ts, because Node strips the types from a .ts file and runs what’s left.

That also means the tool that strips the types isn’t checking them. It deletes, and moves on, which is why the check is a command of its own. And anything that only arrives while the program runs, such as JSON from fetch, was never checked at all.

The bundler

Now the tool that wrote the long line. Here’s the problem it solves. The page’s first line imports a package by its bare name, "date-fns". Node knows packages live in node_modules. A browser doesn’t. Serve the .js version of this page with a plain file server and the browser gives up on that first line:

Uncaught TypeError: Failed to resolve module specifier "date-fns". Relative references must start with either "/", "./", or "../".

Even if it could follow the import, it would find about three hundred files behind it, and each one is another request. A bundler does that walk ahead of time, on your computer. It starts from the page, follows every import, into node_modules too, and collects each file it reaches. Then it writes them out as one file, which the browser loads with a single request. Vite is a bundler:

npx vite build
vite v8.3.8 building client environment for production...
transforming...
✓ 309 modules transformed.
rendering chunks...
computing gzip size...
dist/index.html                 0.21 kB │ gzip: 0.16 kB
dist/assets/index-Cyl0Tnjd.js  20.29 kB │ gzip: 5.98 kB

✓ built in 31ms

It reached 309 files and wrote two. The rewritten dist/index.html asks for the new script by name, /assets/index-Cyl0Tnjd.js, and the page in dist loads with two requests. webpack, Rollup, esbuild and Parcel are bundlers too.

Smaller on the way

On the way through, the bundler makes the code smaller, in three ways.

First, it leaves out whatever nothing imports. date-fns exports more than two hundred functions, and the page uses two, so those two go in, with the helpers they need. withTax goes too, since nothing imports it. Leaving code out this way is called tree shaking.

Second, it strips the types.

Third, it minifies. Comments and line breaks go, and every name that can’t be seen from outside the file gets a shorter one. It’s the same program in fewer characters. Search the built file for the page’s function:

grep -o "function ue(e,t){return e+t}" dist/assets/*.js

That’s orderTotal, renamed ue, its parameters e and t. The bundler also names the file after a fingerprint of its contents, the eight characters after index-. Change a single character of your code and the name changes, so a browser can keep its copy for as long as the name stays the same. If you ask, a bundler will also rewrite newer syntax for older browsers (Vite’s build.target setting).

The dev server

A build is for shipping. While you work, the same tool has a faster mode, the dev server, and it skips the packing. The browser asks for a file, and the server strips its types and sends it on the spot. It sends the date package as one file it prepared ahead of time, so the page asks for six files, not three hundred. Save a file in your editor and the page reloads by itself. That’s the dev script, the one you leave running all day.

One command

Now join them up. A script can run several commands in a row, with a double ampersand between them, and each one starts only if the one before it passed. That’s what && means in JavaScript too: go on only if the left side is true. Add two more scripts:

{
  "name": "checkout",
  "private": true,
  "type": "module",
  "scripts": {
    "dev": "vite",
    "test": "node --test",
    "check": "node --test && oxlint && tsc",
    "build": "npm run check && vite build"
  },
  "dependencies": {
    "date-fns": "^4.4.0"
  },
  "devDependencies": {
    "@types/node": "^26.6.6",
    "oxlint": "^1.93.0",
    "prettier": "^3.10.1",
    "typescript": "^7.0.2",
    "vite": "^8.3.8"
  }
}

check runs the tests, then the linter, then the type checker. build runs check first and the bundler last. Put the string bug back (orderTotal(price.value, shipping) in main.ts), delete the dist folder, and build:

npm run build

The test passes, the linter finds nothing, and the type checker stops on the same error as before. The bundler never starts, and no dist folder is written. The bug can’t reach a visitor, because the only way to the browser goes through the checks. Put the fix back and npm run build runs all four to the end. On a team, a server runs the same check on every change.

Back to the one line

Now the line from the start can be read. It opens with 670 characters of the bundler’s own, a helper that preloads modules in browsers that can’t. Most of the rest is date-fns, or the small part of it this page uses. Near the end is your own function, under its short name, and after it the lines that build the page. The types are gone. withTax is gone. The test file was never in it.

When you need to debug the short version, ask the bundler for a source map:

npx vite build --sourcemap

Beside the script it writes index-Cyl0Tnjd.js.map, a file that tells the browser’s developer tools which line of yours each piece came from, and the script’s last line points to it. The map is about 137 kB, and the browser asks for it only once its developer tools are open. The browser runs the short version, and you keep reading your own.

Summary

  • A tool is a program that reads your code as text. Some report what they find, others write new code. Install them with --save-dev, and visitors never download them.
  • npm scripts give a project’s commands short names in package.json. npm run dev runs one; npm test skips the run. Inside a script, the project’s installed tools are found by name.
  • A test calls your code and compares the answer with the one you expect. node --test runs every .test.js file.
  • A linter reads your code for patterns that usually mean a mistake; a formatter rewrites only its layout.
  • TypeScript adds types after names, and tsc checks every call without running a line. Types exist while you write and are stripped before the code runs, so the check is a command of its own.
  • A bundler follows every import from the page, writes one file, leaves out what nothing imports, strips the types, shortens the names and fingerprints the file’s name. A source map leads back to your lines.
  • Joined with && in one build script, the checks become the only road from your editor to the browser.
Video transcript

Intro

This is the JavaScript that one small checkout page sends to your browser. It's a single line, twenty thousand characters long, and its names are one or two letters each. Nobody typed that. Here's what the developer wrote: two short files, twenty-two lines, with names you can read. Open almost any large website and you'll find the same gap. So what happens to code between the editor and the browser? Today, we find out.

By the end of this video, you'll understand three things. One: npm scripts: how a project gives each of its commands a name. Two: the tools that check your code before it runs: tests, a linter, and TypeScript. Three: the bundler: the tool that packs your files for the browser, and the one that wrote that long line.

What a tool is

Start with what a tool is. To a browser, your file is a program to run. To a tool, it's text to read. Every tool in this video is a program of its own, and it does one of two things with that text. Some read your code and report what they find. The others read it and write new code. You install them from npm, like any package, with one flag added: save-dev. That lists them in package dot json as dev dependencies: packages you need while you work on the project, and that visitors never download. None of them changes the language the browser runs. It's still the JavaScript you know, with a few programs standing around it.

npm scripts

Each tool is started by a command, and commands are easy to forget. So package dot json has a section for them, called scripts. Every row is a name, and the command it stands for. Type npm run and a name, and npm runs that command. This buys you two things. First, npm knows where the project's tools are installed. Type a tool's name straight into the terminal: command not found. Put it in a script, and it runs. Second, the names travel with the project. Anyone who downloads it types npm install, and then the same short names you do: dev, test, build. A few names are common enough that npm lets you skip the word run, and npm test is one of them. For a one-off, npx and a tool's name does the job without a script.

Tests

The first checker is one you write yourself. A test is a few lines of code that call your code and compare its answer with the one you expect. This page has a function that adds shipping to a price. So the test hands it a price of one hundred and shipping of five, and says the answer must equal one hundred and five. Node has a test runner built in: run node with the flag test, and it finds every file whose name ends in dot test dot js. One check mark. The test passed. Now break the function, so it forgets the shipping, and run npm test again. A cross, and two numbers: what it got, and what it wanted. Nobody had to open the page to see that. From now on, this function can't break quietly.

Linters and formatters

The second checker doesn't run your code at all. It reads it. A linter carries a long list of patterns that usually mean a mistake, and flags every one it finds. Here it finds a variable, shipping, that's declared and never used. And it's right: further down, the number five is typed in by hand, where that variable should be. A formatter is the linter's cousin. It isn't looking for mistakes. It rewrites the layout, the spaces, the line breaks and the quotes, the same way in every file, so a team never argues about style. The best-known linter is ESLint, and the best-known formatter is Prettier.

TypeScript

Back to that passing test. Open the page, type one hundred into the price field, and the total reads one thousand and five dollars. The test passed, and the page is wrong. A field's value is always a string, and a string plus a number glues the two together. The test never tried a string. A test covers the cases you thought of. TypeScript covers the ones you didn't. It's JavaScript with one thing added: after a name, you can write the type you expect. Price, colon, number. Then its checker, a command called tsc, reads every file and follows every call, without running a line. It stops on this one: argument of type string is not assignable to parameter of type number. Wrap the value in Number, and the error is gone.

Types are erased

There's a catch. No browser runs TypeScript. Hand one a file with types in it, and it stops at the first colon: a syntax error. So before the code runs anywhere, the types come out. And that's all it takes. Delete every annotation, and what's left is plain JavaScript, the code you'd have written without them. That tells you what types are. They exist while you write, and they're gone when the program runs. It also means the tool that strips them isn't checking them. It deletes, and moves on. Which is why the check is a command of its own.

The bundler

Now the last tool, the one that wrote the line we started with. Here's the problem it solves. The page's script imports a package by its bare name. Node knows where packages are kept. A browser doesn't, and it gives up on that first line. Even if it could follow the import, it would find about three hundred files behind it, and each one is a request. A bundler does that walk ahead of time, on your computer. It starts from the page, follows every import, into node modules too, and collects each file it reaches: three hundred and nine. Then it writes them out as one file, which the browser loads with a single request. This bundler is called Vite.

Smaller on the way

On the way through, the bundler makes the code smaller, in three ways. First, it leaves out whatever nothing imports. That date package exports more than two hundred functions, and the page uses two, so those two go in, with the helpers they need. That's called tree shaking. Second, it strips the types. Third, it minifies. Comments and line breaks go, and every name that can't be seen from outside gets a shorter one: orderTotal ends up as a couple of letters. It's the same program in fewer characters. And it names the file after a fingerprint of its contents. Change a single character in your code, and the name changes, so a browser can keep its copy for as long as the name stays the same.

The dev server

A build is for shipping. While you work, the same tool has a faster mode: a dev server. It skips the packing. The browser asks for a file, and the server strips its types and sends it on the spot, so it's ready in a fraction of a second. Save a file in your editor, and the page reloads by itself. That's the script named dev, and it's the one you leave running all day.

One command

Now join them up. A script can run several commands in a row, with a double ampersand between them, and each one starts only if the one before it passed. So check runs the tests, then the linter, then the type checker. And build runs check first, and the bundler last. Put the string bug back, and type npm run build. The tests pass. The linter passes. The type checker stops, and the bundler never starts. No file is written. The bug can't reach a visitor, because the only way to the browser goes through the checks.

Back to the one line

Which brings us back to the single line we started with. Now you can read it. Most of it is the date package, or the small part of it this page uses. Near the end is your own function, under its new short name, and after it, the lines that build the page. The types are gone. The function nothing imported is gone. The tests were never in it, because no import leads to them. And when you need to debug it, the bundler can write a source map beside it: a file that tells the browser's developer tools which line of yours each piece came from. The browser runs the short version, and you keep reading your own.

In one line

That's JavaScript's build tools in one line: npm scripts give a project's commands their names; tests, a linter and TypeScript check the code before it runs; and a bundler packs what's left into the one file the browser gets.

Next time

Next time, in the last episode of this series, we start with an empty folder and build one small app, from what every episode so far has taught.

Learn more