npm, package.json and Vite: What npm install Fetches and How Vite Serves and Builds Your Page
Three names in package.json became 17 packages in node_modules. Follow npm install to the registry and back, read the lock file, then watch Vite serve one file per request in dev and build three hashed files for production.
What you will learn
- Read package.json: scripts, dependencies vs devDependencies, and what ^ and ~ allow
- Explain what npm install downloads, why node_modules is flat, and what package-lock.json pins
- Tell a bare package import from a ./ path import
- Describe how the Vite dev server answers one file per request, what HMR does, and what npm run build puts in dist
Before you start
- JavaScript modules: import and export
- Running a file with Node
A front-end project starts as a list of names and ends as a few files on a web server. In between, npm fetches what the list names and Vite turns your files into a page. This article follows a tiny "Today's plan" project through every step, with the real versions, file counts and sizes from one run.
package.json: the project's ID card
{
"name": "s01l04-npm-vite",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview"
},
"devDependencies": {
"typescript": "~6.0.3",
"vite": "^8.3.4"
},
"dependencies": {
"dayjs": "^1.11.23"
}
}
name is the project's id, private: true means npm will never publish it to the registry by mistake, and version is the project's own version. "type": "module" tells Node the files use import and export.
The scripts are named shortcuts. On npm run dev, npm looks up dev and finds the command vite. Vite was never installed globally, so npm runs it from node_modules/.bin, where npm install placed small launchers: nanoid, rolldown, tsc, tsserver and vite.
dependencies vs devDependencies
devDependencies are tools for building: typescript and vite run on your machine while you work. dependencies are code the page itself runs. npm install dayjs (a tiny date library) downloaded it, printed added 1 package, and wrote the dependencies block for us.
The build proves the difference. The production JavaScript file, 8.62 kB, contains the dayjs date code, but nothing from vite or typescript. Dependencies end up in what your users download; devDependencies only help you build it.
What ^ and ~ allow
A version has three numbers: major, minor and patch. In 8.3.4, 8 is the major, 3 the minor and 4 the patch.
"vite": "^8.3.4": the caret accepts 8.3.4 and anything newer while the major stays 8.npm lsshowed vite 8.3.5 installed, the newest 8.x on the registry at the time."typescript": "~6.0.3": the tilde is stricter, patch updates only. TypeScript 7.0.2 was already out, but the tilde kept the project on 6.0.3."dayjs": "^1.11.23"installed as exactly 1.11.23, because that was already the newest.
A new major version never sneaks in by itself.
What npm install really does
npm install
added 17 packages, and audited 18 packages in 6s
8 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
npm read three names from package.json and asked the registry, npmjs.org, about each one. The registry said vite 8.3.5 needs five more packages, so npm asked about those, and about theirs. The list grew from 3 to 17. Each package arrived as a compressed tarball, such as vite-8.3.5.tgz, and was unpacked into node_modules. npm also wrote package-lock.json, 822 lines long.
Why 17 when we asked for 3? vite's own package.json lists lightningcss, picomatch, postcss, rolldown and tinyglobby, and those have packages of their own. Here's part of npm ls --all, with the optional platform builds left out:
+-- dayjs@1.11.23
+-- typescript@6.0.3
`-- vite@8.3.5
+-- lightningcss@1.33.0
| +-- detect-libc@2.1.2
| `-- lightningcss-win32-x64-msvc@1.33.0
+-- picomatch@4.0.7
+-- postcss@8.5.32
| +-- nanoid@3.3.20
| +-- picocolors@1.1.1
| `-- source-map-js@1.2.2
+-- rolldown@1.2.16
| +-- @oxc-project/types@0.156.0
| +-- @rolldown/binding-win32-x64-msvc@1.2.16
| `-- @rolldown/pluginutils@1.0.1
+-- tinyglobby@0.2.17
| +-- fdir@6.5.0
| | `-- picomatch@4.0.7 deduped
| `-- picomatch@4.0.7 deduped
The win32-x64 packages are the builds for this operating system only. picomatch is needed three times but marked deduped: npm lays the whole tree out flat, 17 folders side by side, and stores picomatch once.
The lock file pins every version
Here is the start of the vite entry in package-lock.json:
"node_modules/vite": {
"version": "8.3.5",
"resolved": "https://registry.npmjs.org/vite/-/vite-8.3.5.tgz",
"integrity": "sha512-z1YpjieJ9g0ebTmQ...",
"dev": true,
package.json says ^8.3.4, the range you accept. The lock says 8.3.5, exactly what you got. resolved is the exact file downloaded, and integrity is a sha512 fingerprint that npm checks every download against (shortened here). When a teammate runs npm install next month, npm reads the lock first and installs the same versions, even if newer ones exist by then. Commit both files.
Import by name or by path
import './style.css'
import dayjs from 'dayjs'
import { tasks } from './tasks.ts'
// no ./ in 'dayjs': a PACKAGE, found in node_modules
// ./ in './tasks.ts': OUR file, next to this one
const app =
document.querySelector<HTMLDivElement>('#app')!
const items = tasks.map(t => `<li>${t}</li>`).join('')
app.innerHTML = `
<h1>Today's plan</h1>
<p>${dayjs().format('dddd, D MMMM')}</p>
<ul>${items}</ul>
`
'dayjs' has no ./, so it's a bare name, which means a package. The tools look in node_modules/dayjs, read its package.json, and its main field points to dayjs.min.js. './tasks.ts' starts with ./, so it's our own file in the same folder, src/tasks.ts. And import './style.css' imports no names at all; it just loads the styles.
Drop the ./ and write from 'tasks.ts', and Vite searches node_modules for a package called tasks.ts:
[vite] Internal server error: Failed to resolve import "tasks.ts" from "src/main.ts". Does the file exist?
The dev server: the browser asks, Vite answers
> s01l04-npm-vite@0.0.0 dev
> vite
VITE v8.3.5 ready in 434 ms
➜ Local: http://localhost:5173/
➜ Network: use --host to expose
It's ready so fast because nothing is built yet. The browser opens the address and asks for /. Vite sends index.html with one extra line in the head, a script for /@vite/client. The page's own script tag asks for /src/main.ts, and Vite turns that TypeScript into JavaScript on the spot. Then main.ts's imports trigger requests for the CSS, dayjs and tasks.ts. One request per file:
/ text/html
/src/main.ts text/javascript
/src/style.css text/javascript
/node_modules/.vite/deps/dayjs.js?v=dab583b3 text/javascript
/src/tasks.ts text/javascript
Look at what the browser actually received for main.ts. The type <HTMLDivElement> and the ! are gone, because browsers only read JavaScript. './tasks.ts' became "/src/tasks.ts", a URL from the site root. The bare 'dayjs' became a file under /node_modules/.vite/deps/, where Vite pre-bundled the package once into one file a browser can load. And the CSS came back as a small JavaScript module that injects a style tag and ends with import.meta.hot.accept().
Save, and the page updates
Vite watches your files. Change the heading colour in style.css from #2563eb to #16a34a and save:
[vite] (client) hmr update /src/style.css
HMR is hot module replacement. Only the style tag is swapped, the heading turns green, and nothing on the page is lost. Now change the heading text in main.ts and save:
[vite] (client) page reload src/main.ts
This time the whole page reloads by itself. The difference is that import.meta.hot.accept() line: the CSS module says "I can replace myself", and main.ts has no such line, so Vite plays safe.
npm run build: a few hashed files
> s01l04-npm-vite@0.0.0 build
> tsc && vite build
vite v8.3.5 building client environment for production...
transforming...
✓ 7 modules transformed.
rendering chunks...
computing gzip size...
dist/index.html 0.51 kB │ gzip: 0.32 kB
dist/assets/index-iCIINFuW.css 0.09 kB │ gzip: 0.10 kB
dist/assets/index-C0CpBIdJ.js 8.62 kB │ gzip: 3.82 kB
✓ built in 144ms
tsc checks the types first and writes nothing. The && runs vite build only if that passed, so a type error stops the build. Vite then bundles the modules into three files. The gzip column is what the browser actually downloads.
The letters in the names are a hash of the content. Add one task to tasks.ts and rebuild: the JavaScript file becomes index-HrOpFh6M.js (8.64 kB) while the CSS keeps its name. Undo the change and index-C0CpBIdJ.js comes back. Same name means same content, so a browser can cache a file safely, and new content always gets a new name.
The built dist/index.html has Vite's own script and stylesheet lines with those hashed names, and the original /src/main.ts line is gone. dist is plain HTML, CSS and JavaScript; any web server can host it, and nothing from node_modules is needed.
What goes into Git
Commit the small text files: package.json, package-lock.json, index.html, tsconfig.json, src/ and public/. Skip node_modules (npm install rebuilds it) and dist (npm run build rebuilds it); the project's .gitignore already lists both. On a new machine: clone, npm install, npm run dev, and the lock file gives you the same 17 packages.
Keep projects in a normal local folder, not a cloud-synced one. npm install writes thousands of small files very fast (2,379 files for one small React project in this course), and on a Google Drive folder it failed with EBADF, a bad file descriptor. The same project on the local disk installed fine.
Quick recap
| Piece | Job |
|---|---|
package.json | what the project needs, plus script shortcuts |
^ / ~ | minor and patch updates / patch only |
npm install | fetches the whole tree, lays it out flat in node_modules |
package-lock.json | exact versions, URLs and fingerprints; commit it |
'dayjs' vs './tasks.ts' | a package vs your own file |
npm run dev | one file per request; CSS swapped in place, other changes reload |
npm run build | type check, bundle, content-hashed files in dist |
If you come from Python, package.json plays the role of pyproject.toml, node_modules is a per-project environment like a virtual environment, and the lock file is like a pinned requirements file.
Try it yourself
Run npm ls and compare each installed version with its range in package.json. Then change one CSS colour with npm run dev running and watch for the hmr update line, and run npm run build twice to confirm the file names don't change when the content doesn't.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
One Request, Two Answers: the Same Post as an HTML Page and as JSON
Ask a Django blog for the same post twice: once as a 12,731-byte HTML page built by a template, once as 2,976 bytes of JSON built by a serializer. Compare the headers, see who builds the page, and why the server still owns every write.
A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx
Make a blog design from a prompt in Figma Make, download src.zip, unzip it with Python's zipfile module, and read the two files that matter: App.tsx with its selectedPost state and BlogCard.tsx with its props.
How a Web Page Works: HTML Tags, Elements and Attributes
A web page is a text file full of labelled pieces. Learn tags, attributes and nesting with three tiny pages, and see what breaks when an attribute or a closing tag is wrong.
Semantic HTML: header, nav, main, aside and footer as Page Landmarks
The same page written as div soup and with semantic tags looks identical, but only one gives screen readers and search engines landmarks and an outline. Plus tables, div, span and the one-main rule.
