Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Lab · 30 min · revision 2

Lab: From Empty Folder to a Linted, Tested, Built Project

Assemble the whole toolchain by hand: a manifest with scripts and a committed lockfile, a Vite build of the list, an ESLint flat config that catches an unused variable, a Prettier check and a Vitest run.

Contentsand lesson path

What you will learn

  • Manage dependencies with npm or pnpm: package.json scripts, semantic-version ranges, committed lockfiles, dev vs runtime dependencies, and vulnerability audits.
  • Scaffold and configure a Vite project and explain what the dev server and the production build do (module graph, bundling, minification, content hashing, source maps, public environment variables).
  • Enforce code quality with an ESLint flat config, Prettier and a Vitest test script, wired into npm scripts so a failing check blocks a commit or merge.

01. Goal and setup

By the end of this lab you will have built, from an empty folder, the project that the shopping-list practice starts from: a package.json with npm scripts and a committed lockfile, the list running under npm run dev, a production build in dist/, and three guardrails — ESLint, Prettier and Vitest — chained into one check script. Nothing here uses a scaffold: every file is written deliberately, so you know what each one does.

You need: Node.js 22.13 or later and npm (check with node --version and npm --version; this lab ran on Node v22.23.2 with npm 10.9.8, and Node 26 is the current Active LTS) and a terminal. Everything installs locally into the project, never globally. The install command pins the versions this lab ran with — Vite 8.4.0, ESLint 10.15.0 (with @eslint/js 10.0.1 and globals 17.14.0), Prettier 3.10.1 and Vitest 5.1.2 — so the version numbers in the outputs match yours.

The finished layout:

Project layout
shopping-list/
├── .gitignore            node_modules/ and dist/
├── .prettierrc.json      Prettier options
├── .prettierignore       files Prettier must leave alone
├── eslint.config.js      ESLint flat config
├── index.html            the page Vite serves and builds
├── package.json          manifest and scripts
├── package-lock.json     exact versions (committed)
├── vite.config.js        build options
└── src/
    ├── list.js           pure list logic, testable
    ├── list.test.js      Vitest tests for list.js
    └── main.js           DOM wiring, the entry module

02. Step 1: create the manifest and install the tools

Terminal
mkdir shopping-list && cd shopping-list
npm init -y
npm pkg set type=module
npm pkg set scripts.dev=vite scripts.build="vite build" \
  scripts.preview="vite preview" scripts.lint="eslint ." \
  scripts.format="prettier --write ." \
  scripts.format:check="prettier --check ." \
  scripts.test="vitest run"
npm pkg delete main description

npm init -y writes a minimal manifest; npm pkg set edits it without hand-formatting JSON, and the \ continues a command across lines. Now install the toolchain. Everything is a dev dependency — none of it ships to users (why):

Terminal
npm install --save-dev [email protected] [email protected] @eslint/[email protected] \
  [email protected] [email protected] [email protected]
Illustrative output (counts and timing will differ)
added 115 packages, and audited 116 packages in 5m

31 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

Three files resulted: node_modules/ (the installed packages), package.json (your ranges, plus the new devDependencies) and package-lock.json (the exact tree). Create the ignore file now, before the first commit:

Text · .gitignore
node_modules/
dist/

Both entries are regenerable: npm ci rebuilds node_modules/ from the lockfile, and npm run build rebuilds dist/ from source. Commit the manifest and the lockfile; commit neither folder.

03. Step 2: the application files

The application is the list from the DOM and events skill, now split the way a testable project splits it. All logic lives in list.js as pure functions — data in, data out, no document — and main.js does the DOM wiring around them. That split is not ceremony: it is what makes step 5 possible, because a pure module can be tested in milliseconds without a browser, while the DOM layer stays thin enough to review at a glance. If you followed the DOM lab you have written these pieces before; here they simply move into a real project.

HTML · index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Shopping list</title>
  </head>
  <body>
    <main>
      <h1>Shopping list</h1>
      <label for="filter-input">Filter items</label>
      <input id="filter-input" type="search" autocomplete="off" />
      <ul id="list"></ul>
    </main>
    <script type="module" src="/src/main.js"></script>
  </body>
</html>
JavaScript · src/list.js
// Pure list logic: no DOM here, so it can be tested without a browser.

export function applyFilter(items, query) {
  const needle = query.trim().toLowerCase();
  if (needle === '') return items;
  return items.filter((item) => item.label.toLowerCase().includes(needle));
}
JavaScript · src/main.js
import { applyFilter } from './list.js';

const items = [
  { id: 1, label: 'Oats', done: false },
  { id: 2, label: 'Milk', done: true },
  { id: 3, label: 'Rye bread', done: false },
];

const list = document.querySelector('#list');
const filterInput = document.querySelector('#filter-input');

function render() {
  const visible = applyFilter(items, filterInput.value);
  list.replaceChildren(
    ...visible.map((item) => {
      const li = document.createElement('li');
      li.textContent = item.label;
      return li;
    }),
  );
}

filterInput.addEventListener('input', render);
render();

Start the dev server with npm run dev, open the printed http://localhost:5173/, and type into the filter box — the list narrows as you type. Leave the server running or stop it with Ctrl-C; the remaining steps do not need it.

04. Step 3: ESLint with a flat config

JavaScript · eslint.config.js
import js from '@eslint/js';
import globals from 'globals';

export default [
  js.configs.recommended,
  {
    languageOptions: {
      globals: globals.browser,
    },
    rules: {
      'no-unused-vars': 'error',
      eqeqeq: 'error',
    },
  },
  {
    ignores: ['dist/'],
  },
];

Run npm run lint: it passes, because the three files above are clean. A guardrail you have never seen fire is hard to trust, so introduce a real defect — the kind a hurried edit leaves behind — and watch the gate catch it. Before you run the lint, predict which line, column and rule it will report:

JavaScript · src/sum.js (temporary file)
export function sum(numbers) {
  let total = 0;
  for (const n of numbers) {
    total += n;
  }
  const doubled = total * 2;
  return total;
}
Expected output · npm run lint (the folder part of the path left out)
$ npm run lint

src/sum.js
  6:9  error  'doubled' is assigned a value but never used  no-unused-vars

✖ 1 problem (1 error, 0 warnings)

Read the report the way a CI job would. 6:9 is the line and column; no-unused-vars is the rule that fired, one of a few hundred ESLint ships, each documented with examples of code it flags and how to fix it. The recommended set from @eslint/js catches the everyday categories: variables and parameters that are never used, unreachable code after a return, accidental globals created by a missing declaration, and comparisons whose truthiness does not behave the way the author probably expected.

Fix it by deleting line 6, run npm run lint again (silent, exit 0), then delete the temporary src/sum.js. If your lint ever reports document is not defined in main.js instead, the config above is missing the languageOptions block — ESLint needs the browser globals list, it will not guess.

05. Step 4: Prettier with a check gate

Text · .prettierrc.json and .prettierignore
{ "printWidth": 88, "singleQuote": true }

# .prettierignore:
dist/
package-lock.json

Again, verify the gate by tripping it. Save a badly formatted file, run the check, then let the formatter rewrite it:

JavaScript · src/summary.js as first written (temporary file)
import { applyFilter } from "./list.js";

export function summary(items, query) {
  const visible = applyFilter(items, query);
  const labels = visible.map(function (item) { return item.label; });
  return labels.join(", ");
}
Expected output · npm run format:check
$ npm run format:check
Checking formatting...
[warn] src/summary.js
[warn] Code style issues found in the above file. Run Prettier with --write to fix.
Terminal
npm run format && npm run format:check
Expected output (last lines; --write also lists each file with a time in ms)
> [email protected] format:check
> prettier --check .

Checking formatting...
All matched files use Prettier code style!

Have a look at src/summary.js after the rewrite — quotes and the one-line function changed, nothing else — then delete the temporary file. The workflow from here on: editors format on save (--write), CI only checks (--check).

06. Step 5: Vitest

JavaScript · src/list.test.js
import { describe, expect, it } from 'vitest';
import { applyFilter } from './list.js';

const items = [
  { id: 1, label: 'Oats', done: false },
  { id: 2, label: 'Milk', done: true },
  { id: 3, label: 'Rye bread', done: false },
];

describe('applyFilter', () => {
  it('returns every item for a blank query', () => {
    expect(applyFilter(items, '   ')).toHaveLength(3);
  });

  it('matches case-insensitively', () => {
    expect(applyFilter(items, 'rye')).toEqual([items[2]]);
  });

  it('matches part of a label', () => {
    expect(applyFilter(items, 'bre')).toEqual([items[2]]);
  });
});
Expected output · npm run test (path trimmed; Start at and Duration lines left out)
$ npm run test

 RUN  v5.1.2 <project>


 Test Files  1 passed (1)
      Tests  3 passed (3)

The tests target list.js because it is pure: items in, filtered items out, no DOM. Each test follows the same shape — arrange a known list, act by calling applyFilter, and assert on the result — and each name describes the behaviour it checks, so a failure reads as a sentence about what broke rather than about which line changed.

The script runs vitest run — once, then exits — so it works the same on your machine and in CI. While editing, npx vitest without run starts watch mode and re-runs only the tests a change affects, which is the faster inner loop; the one-shot form is what gates a merge.

07. Step 6: build, then the check chain

JavaScript · vite.config.js
import { defineConfig } from 'vite';

export default defineConfig({
  build: {
    sourcemap: true,
  },
});
Expected output · npm run build (the last line, the build time, left out)
$ npm run build

vite v8.4.0 building client environment for production...
transforming...
✓ 5 modules transformed.
rendering chunks...
computing gzip size...
dist/index.html                0.49 kB │ gzip: 0.30 kB
dist/assets/index-CKUx3slP.js  1.16 kB │ gzip: 0.62 kB │ map: 1.82 kB

If your files match the lab byte for byte and the versions are pinned, your file is also called index-CKUx3slP.js; any change to what ships gives it a new name (how content hashing works). Check the page one last time with npm run preview, which serves dist/ the way a web server would. Finally, chain the gates into one script — edit package.json and add it to "scripts":

JSON · package.json scripts
"check": "npm run lint && npm run format:check && npm run test"
Expected output · npm run check (trimmed; ESLint is silent on success)
$ npm run check
> [email protected] check
> npm run lint && npm run format:check && npm run test

All matched files use Prettier code style!
 Test Files  1 passed (1)
      Tests  3 passed (3)

To prove the lockfile reproduces the environment, wipe the installed packages and restore them from the lockfile alone:

Illustrative output · npm ci (counts and timing will differ)
$ rm -rf node_modules && npm ci
added 117 packages, and audited 118 packages in 2m

32 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

08. Check your understanding

Practice check · 3 questions

What you built

Reason from the project you just assembled.

Q1. Why do .gitignore entries cover node_modules/ and dist/ but not package-lock.json?
Q2. After `npm run build`, a teammate opens `dist/index.html` by double-clicking it and sees a blank page. What is the likely cause?
Q3. You edit package.json to add a dependency but never run npm install. On CI, `npm ci` fails. Why?
Practice only: not graded, not saved, not evidence.

09. Apply it: stretch tasks

  1. Write a failing test for a sortList function that does not exist yet, run npm run test to watch it fail for the right reason, then implement the function until the suite passes. The next lesson turns this into a full workflow with an AI assistant.
  2. Add src/config.js reading VITE_LIST_TITLE with a default, use it in main.js, and rebuild twice to watch the asset name change only when the value actually ships.
  3. Set "private": true in package.json (this project is an app, not a package to publish) and add a README line for each script. When you are ready to put the build online, the deployment skill continues exactly here.

10. Review prompt

Without looking back: name every file you created and its job in one sentence. What does npm ci need before it will install anything? What do lint, format:check and test each report on failure? And which two folders stay out of version control, rebuilt by which commands?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check