Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
⚡ Days 15–22 – Advanced & Async JavaScript  ·  Day 21

Day 21: Modules, npm & Modern Tooling

⏱ 90 min📶 Intermediate → Pro🎯 100% self-study
Day 21 / 30

✅ Today you will learn

  • Why one huge script.js becomes unmaintainable
  • ES modules: named and default export/import
  • Modules in the browser (type="module") and in Node.js
  • npm, package.json, dependencies and scripts
  • Vite for dev and build; ESLint + Prettier for quality

🏢 In the real world

Our shop code now has products, a cart class, formatting helpers, validation rules and API calls – 900 lines in one file. Two developers editing it at the same time overwrite each other’s work, and nobody can find anything. Every company splits code into modules and uses npm tools. This is the setup you will see on day one of a job.

From one file to modules

Folder – a modular shop
sharma-shop/
├── index.html
├── package.json
└── src/
    ├── main.js            ← entry point: wires everything together
    ├── api.js             ← fetchJSON, getProducts, placeOrder
    ├── cart.js            ← export class Cart
    ├── format.js          ← export rupees(), formatDate()
    ├── validate.js        ← export rules, validate()
    └── ui/
        ├── productGrid.js
        └── cartPanel.js

export and import

JavaScript – src/format.js (named exports)
export const GST_RATE = 0.05;

export function rupees(amount) {
  return new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR', maximumFractionDigits: 0 }).format(amount);
}

export const withGst = (amount) => Math.round(amount * (1 + GST_RATE));
JavaScript – src/cart.js (default export)
import { withGst } from './format.js';

export default class Cart {
  #items = [];
  add(product, qty = 1) { this.#items.push({ ...product, qty }); return this; }
  get total() { return withGst(this.#items.reduce((s, i) => s + i.price * i.qty, 0)); }
}
JavaScript – src/main.js
import Cart from './cart.js';                    // default import – any name you like
import { rupees, GST_RATE } from './format.js';   // named imports – exact names in { }
import * as format from './format.js';           // everything as one object

const cart = new Cart().add({ name: 'Kaju Katli', price: 900 }, 2);
console.log(`Total with ${GST_RATE * 100}% GST: ${rupees(cart.total)}`);
console.log(format.withGst(1000));
JavaScript
// The same idea running in Node.js: an inline module demo using data: URLs
const formatModule = `
  export const rupees = n => '₹' + n.toLocaleString('en-IN');
  export default function gst(n) { return Math.round(n * 1.05); }
`;
const url = 'data:text/javascript,' + encodeURIComponent(formatModule);
import(url).then(({ default: gst, rupees }) => {          // dynamic import() returns a promise
  console.log(rupees(gst(180000)));
});
₹1,89,000
TypeExportImportUse for
Namedexport function rupees() {}import { rupees } from './format.js'Several helpers per file (most common)
Defaultexport default class Cart {}import Cart from './cart.js'One main thing per file (components, classes)
Renameexport { a as b }import { rupees as inr } from …Avoid name clashes
Namespace—import * as fmt from './format.js'Grouping helpers
Dynamic—const m = await import('./chart.js')Load heavy code only when needed

Modules in the browser and in Node

HTML – loading a module
<!-- type="module" = deferred automatically, strict mode, own scope, import/export allowed -->
<script type="module" src="src/main.js"></script>
⚠️ Modules need a web server

Opening index.html by double-click (file://) blocks module imports for security. Use VS Code Live Server, npx serve or Vite. Also always include the .js extension in browser imports.

BrowserNode.js
Enable ES modules<script type="module">"type": "module" in package.json, or .mjs files
Older formatGlobal scriptsCommonJS: require() / module.exports
npm packagesThrough a bundler (Vite) or CDN URLsimport express from "express"
Top-level awaitYesYes (in ES modules)

npm and package.json

Terminal – starting a project
# 1. Install Node.js LTS from nodejs.org (includes npm), then check:
node -v
npm -v

# 2. Create a project
mkdir sharma-shop && cd sharma-shop
npm init -y                       # creates package.json

# 3. Add packages
npm install dayjs                 # dependency – shipped with your app
npm install -D vite eslint prettier   # devDependencies – tools for developers only

# 4. Run a script defined in package.json
npm run dev
package.json – the project’s ID card
{
  "name": "sharma-shop",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview",
    "lint": "eslint src",
    "format": "prettier --write src"
  },
  "dependencies": {
    "dayjs": "^1.11.13"
  },
  "devDependencies": {
    "eslint": "^9.15.0",
    "prettier": "^3.3.3",
    "vite": "^5.4.11"
  }
}
File / folderCommit to Git?Why
package.jsonYesLists what the project needs
package-lock.jsonYesExact versions – same install for every developer and server
node_modules/No – add to .gitignoreHuge; recreated with npm install / npm ci
dist/Usually noBuild output; created by npm run build
🧠 What does ^1.11.13 mean?

Semantic versioning: MAJOR.MINOR.PATCH. ^ allows newer minor and patch versions (1.12.0 yes, 2.0.0 no) because major versions may break your code.

Vite: dev server and production build

  1. 1npm create vite@latest sharma-shop -- --template vanilla
  2. 2cd sharma-shop && npm install
  3. 3npm run dev → open http://localhost:5173 – saves reload instantly (hot module replacement)
  4. 4Write modules in src/, import npm packages by name
  5. 5npm run build → optimised, minified files in dist/
  6. 6Upload dist/ to Hostinger, Netlify or GitHub Pages
From zero to a deployed modular app

ESLint and Prettier: automatic code review

ESLint finds problems

  • Unused variables and imports
  • Using a variable before defining it
  • == instead of ===
  • Missing await / unreachable code

Prettier formats code

  • Same indentation and quotes for everyone
  • Line breaks at a fixed width
  • Runs on save in VS Code
  • No more style arguments in code review
eslint.config.js – a minimal modern setup
import js from '@eslint/js';
import globals from 'globals';

export default [
  js.configs.recommended,
  {
    languageOptions: { ecmaVersion: 'latest', sourceType: 'module', globals: globals.browser },
    rules: {
      eqeqeq: 'error',
      'no-unused-vars': 'warn',
      'prefer-const': 'error',
    },
  },
];

🏅 Job skills unlocked today

✔ Split code into ES modules with named and default exports✔ Load modules in the browser and Node.js✔ Manage packages and scripts with npm✔ Develop and build with Vite; enforce quality with ESLint and Prettier

Practice tasks

🏋️ Practice – do it yourself

Task 1: Split the Day 17 Cart example into cart.js, format.js and main.js with exports/imports and run it with Live Server.
Task 2: Create a Vite vanilla project, install dayjs and show “Delivery by: Wed, 28 Oct” using dayjs().add(3, "day").
Task 3: Run npx eslint on your Day 13 form code with eqeqeq and prefer-const enabled and fix every warning.

Quick quiz

🧠 Quick Quiz – test yourself

1. Import a default export from './cart.js':
No braces for default.
2. <script type="module"> is…
Like defer.
3. Which should NOT be committed to Git?
Recreated by npm install.
4. npm install -D vite installs vite as…
Only for development.
5. npm run build with Vite outputs to…
Deploy dist/.

Interview corner

💼 Interview Corner

ES modules vs CommonJS?

ESM uses static import/export, is the standard in browsers and modern Node, supports tree-shaking and top-level await, and loads asynchronously. CommonJS uses require/module.exports, is synchronous and was Node’s original format; interop exists but mixing needs care.

Why use a bundler like Vite?

It serves modules quickly in development with hot reload, resolves npm imports, and for production bundles, minifies, tree-shakes, splits code and fingerprints file names for caching.

Summary

  • One responsibility per module; export what others need.
  • Named exports for helpers, default for the main thing; type="module" in HTML.
  • npm + package.json + lock file; never commit node_modules.
  • Vite for dev/build; ESLint finds bugs, Prettier formats.
➡️ Next

Day 22: useful browser APIs – IntersectionObserver, clipboard, share, geolocation, URL parameters and history.

Frequently Asked Questions

Do I need Vite for small sites?
No – plain <script type="module"> files work fine for small projects. Use Vite when you need npm packages, many files or React.
npm, yarn or pnpm?
All install the same packages. npm comes with Node and is fine; teams pick one and stick to it.
← JavaScript (30 Days)
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

Next topicDay 22: Useful Browser APIs Your progress: 21 / 30 (70%) · Lesson 22 / 30 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free