Skip to content

Intermediate · Async JavaScript, modules and tools · topic 43 of 64 · 35 min

Modules, npm and Vite

Explanation

ES modules let you split code into small files that export what others may use and import what they need. npm installs other people's packages and runs your project's scripts, all described in package.json. Vite starts a new project in one command, gives you a fast dev server, and builds small optimised files for hosting.

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.

Think of it like this: Think of a steel tiffin box with separate compartments: rice in one, dal in another, sabzi in the third. Nothing mixes by accident, and you open only the compartment you need. Modules are the compartments of your code.
javascript
// 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
Named exports are imported in { }, the default export without braces
html
<script type="module" src="./js/main.js"></script>
type="module" turns on import/export; module scripts are deferred automatically
Named exportDefault export
How many per fileAs many as you likeAt most one
Exportexport function addGst() {}export default function formatPrice() {}
Importimport { addGst } from './money.js'import formatPrice from './money.js'
Name when importingMust 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.

json
{
  "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"
  }
}
scripts are commands; dependencies ship with the app; devDependencies are tools for building
FieldWhat goes thereInstall with
dependenciesCode your app needs when it runs in the browser (a date library, a chart library)npm install dayjs
devDependenciesTools only for building and checking (Vite, Prettier, ESLint, Vitest)npm install -D prettier
bash
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 globally
The npm commands you will use every day

The ^ 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.

Careful: Never commit node_modules: it is huge and npm install rebuilds it. Do commit package-lock.json: it records the exact version of every package, so your teammate and your server install the same thing you tested.

Start a project with Vite

bash
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
From nothing to a running project in about a minute
Dev server (npm run dev)Production build (npm run build)
ForYou, while codingReal visitors
SpeedStarts fast, updates the page as you saveTakes a little time once
OutputNothing saved; served from memorySmall, 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.
Tip: npx runs a package's command (from your project, or downloaded for that one run) without a global install. npm create vite@latest works the same way.

Watch the lesson

Modules, npm and Vite · 1/7

export -> import

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)

Task 1 · Code · Javascript

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"].

Task 2 · Code · Javascript

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.

Task 3 · Practice

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

Question 1

1.In import formatPrice, { addGst } from './money.js'; which one is the default export?

Question 2

2.Prettier is only used while you write code. Where should it go?

Question 3

3.Which of these should you NOT commit to Git?

Question 4

4.package.json has "dayjs": "^1.11.13". Which version can npm install?

Question 5

5.What does npm run build do in a Vite project?

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.

← Previous: async/await and error handling