Intermediate · Async JavaScript, modules and tools · topic 43 of 64 · 35 min
Modules, npm and Vite
Explanation
Why split code into modules?
One app.js with 2,000 lines is hard to read, and every variable in a classic script is shared with every other script, so names clash. A module is one file with its own private scope. It shares only what it exports, and it takes only what it imports.
// money.js
export const GST_RATE = 0.18; // named export
export function addGst(amount) { // named export
return Math.round(amount * (1 + GST_RATE));
}
export default function formatPrice(amount) { // default export (one per file)
return `Rs ${amount.toLocaleString('en-IN')}`;
}
// main.js
import formatPrice, { addGst, GST_RATE } from './money.js';
console.log(formatPrice(addGst(1000))); // Rs 1,180<script type="module" src="./js/main.js"></script>| Named export | Default export | |
|---|---|---|
| How many per file | As many as you like | At most one |
| Export | export function addGst() {} | export default function formatPrice() {} |
| Import | import { addGst } from './money.js' | import formatPrice from './money.js' |
| Name when importing | Must match (or rename with as) | You choose any name |
- In the browser, paths start with ./ or ../ and include the .js ending.
- Each module runs once, even if many files import it.
- Modules use strict mode and have top-level await.
- Modules do not work from a file:// address; open the page through a local server (for example VS Code Live Server or Vite).
npm and package.json
npm (Node Package Manager) comes with Node.js. It downloads packages (code written by others) from the npm registry and runs commands for your project. package.json is the project's ID card: its name, its scripts and the packages it needs.
{
"name": "kirana-shop",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"dayjs": "^1.11.13"
},
"devDependencies": {
"vite": "^7.0.0"
}
}| Field | What goes there | Install with |
|---|---|---|
| dependencies | Code your app needs when it runs in the browser (a date library, a chart library) | npm install dayjs |
| devDependencies | Tools only for building and checking (Vite, Prettier, ESLint, Vitest) | npm install -D prettier |
npm install # install everything listed in package.json
npm install dayjs # add a dependency
npm install -D eslint # add a devDependency
npm run dev # run the "dev" script
npm ci # clean install exactly from package-lock.json
npx prettier --write . # run a package's command without installing it globallyThe ^ in "^1.11.13" is a version range. Versions have three numbers: major.minor.patch. ^ means "this version or any newer one with the same major number", so ^1.11.13 accepts 1.12.0 but not 2.0.0, because a new major version may break your code.
Start a project with Vite
npm create vite@latest kirana-shop
# choose a framework (Vanilla is plain JavaScript) and a variant
cd kirana-shop
npm install
npm run dev # dev server, usually at http://localhost:5173
npm run build # optimised files in the dist folder
npm run preview # check the built site locally| Dev server (npm run dev) | Production build (npm run build) | |
|---|---|---|
| For | You, while coding | Real visitors |
| Speed | Starts fast, updates the page as you save | Takes a little time once |
| Output | Nothing saved; served from memory | Small, combined files in dist/ to upload to hosting |
Choosing safe packages
- Do you need it? A 5-line function is better than a new package.
- Is it popular and maintained? Check weekly downloads and the date of the last release on npmjs.com.
- How big is it? Every kilobyte is downloaded by phones on slow networks.
- Check the exact name: attackers publish look-alike names with one letter changed.
- Run npm audit to list known security problems in your packages, and update them.
Watch the lesson
Modules, npm and Vite · 1/7
Big projects are split into modules: small files that export what others may use.
Prefer a video by a teacher? Find free videos on “javascript es modules npm package.json vite tutorial for beginners” on YouTube ↗
In real life: A small shop billing app
A developer builds a billing page for a kirana shop with Vite. The code is split into modules: money.js for GST and price formatting, cart.js for the cart logic, and main.js that connects them to the page. A date library is a dependency, while Vite and Prettier are devDependencies. node_modules is in .gitignore, package-lock.json is committed, and npm run build makes a dist folder that is uploaded to free hosting.
Practice (0/3 done)
Write listCommands(pkg). pkg is a package.json object. Return an array with the command to run each script, in order, like ["npm run dev", "npm run build"]. If pkg has no scripts field, return []. Example: { scripts: { dev: "vite", build: "vite build" } } gives ["npm run dev", "npm run build"].
Write caretAllows(range, version) for versions 1.0.0 and above. range looks like "^1.4.2" and version like "1.9.0". Return true when npm would accept the version: the major number is the same, and the version is equal to or newer than the range version. Compare numbers, not text: 1.10.0 is newer than 1.9.0. Examples: caretAllows("^1.4.2", "1.10.0") is true, caretAllows("^1.4.2", "2.0.0") is false, caretAllows("^1.4.2", "1.4.1") is false.
Install Node.js (the LTS version from nodejs.org), then create a project with npm create vite@latest (choose Vanilla). Run it with npm run dev. Split the code into at least three modules (for example money.js, cart.js and main.js) with both a named and a default export. Install Prettier as a devDependency and add a "format" script. Finally run npm run build and open the dist folder.
Quick quiz
Read more (free)
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.