दिन 21: Modules, npm और Modern Tooling
✅ आज आप सीखेंगे
- एक बड़ी script.js क्यों संभालना मुश्किल हो जाती है
- ES modules: named और default export/import
- Browser (type="module") और Node.js में modules
- npm, package.json, dependencies और scripts
- Dev और build के लिए Vite; quality के लिए ESLint + Prettier
🏢 असली दुनिया में
हमारे shop code में अब products, cart class, formatting helpers, validation नियम और API calls हैं – एक file में 900 lines। एक साथ edit करने वाले दो developers एक-दूसरे का काम overwrite करते हैं, और कुछ मिलता नहीं। हर company code को modules में बाँटती है और npm tools इस्तेमाल करती है। Job के पहले दिन आप यही setup देखेंगे।
एक file से modules तक
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.jsexport और import
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));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)); }
}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));// 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)));
});| प्रकार | Export | Import | कब |
|---|---|---|---|
| Named | export function rupees() {} | import { rupees } from './format.js' | हर file में कई helpers (सबसे आम) |
| Default | export default class Cart {} | import Cart from './cart.js' | हर file में एक मुख्य चीज़ (components, classes) |
| नाम बदलना | export { a as b } | import { rupees as inr } from … | नामों का टकराव रोकना |
| Namespace | — | import * as fmt from './format.js' | Helpers को group करना |
| Dynamic | — | const m = await import('./chart.js') | भारी code सिर्फ़ ज़रूरत पर |
Browser और Node में modules
<!-- type="module" = deferred automatically, strict mode, own scope, import/export allowed --> <script type="module" src="src/main.js"></script>
Double-click (file://) से index.html खोलने पर security के कारण module imports रुक जाते हैं। VS Code Live Server, npx serve या Vite लें। Browser imports में हमेशा .js extension लिखें।
| Browser | Node.js | |
|---|---|---|
| ES modules चालू | <script type="module"> | package.json में "type": "module", या .mjs files |
| पुराना format | Global scripts | CommonJS: require() / module.exports |
| npm packages | Bundler (Vite) या CDN URLs से | import express from "express" |
| Top-level await | हाँ | हाँ (ES modules में) |
npm और package.json
# 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
{
"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 / folder | Git में commit? | क्यों |
|---|---|---|
| package.json | हाँ | Project को क्या चाहिए |
| package-lock.json | हाँ | सटीक versions – हर developer और server पर एक जैसा install |
| node_modules/ | नहीं – .gitignore में | बहुत बड़ा; npm install / npm ci से दोबारा बनता है |
| dist/ | आमतौर पर नहीं | Build output; npm run build बनाता है |
Semantic versioning: MAJOR.MINOR.PATCH। ^ नए minor और patch versions की अनुमति देता है (1.12.0 हाँ, 2.0.0 नहीं) क्योंकि major versions आपका code तोड़ सकते हैं।
Vite: dev server और production build
- 1npm create vite@latest sharma-shop -- --template vanilla
- 2cd sharma-shop && npm install
- 3npm run dev → http://localhost:5173 खोलें – save करते ही reload (hot module replacement)
- 4src/ में modules लिखें, npm packages नाम से import करें
- 5npm run build → dist/ में optimised, minified files
- 6dist/ को Hostinger, Netlify या GitHub Pages पर upload करें
ESLint और Prettier: अपने-आप code review
ESLint समस्याएँ ढूँढता है
- बेकार variables और imports
- Define से पहले variable का उपयोग
- === की जगह ==
- छूटा await / न पहुँचने वाला code
Prettier code format करता है
- सबके लिए एक जैसा indentation और quotes
- तय चौड़ाई पर line breaks
- VS Code में save पर चलता है
- Code review में style बहस ख़त्म
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
Practice tasks
🏋️ Practice – ख़ुद करें
Quick quiz
🧠 Quick Quiz – ख़ुद को जाँचें
Interview corner
💼 Interview Corner
ES modules बनाम CommonJS?
ESM static import/export लेता है, browsers और आधुनिक Node में standard है, tree-shaking और top-level await support करता है, और async load होता है। CommonJS require/module.exports लेता है, synchronous है और Node का मूल format था; interop है पर मिलाते समय सावधानी चाहिए।
Vite जैसा bundler क्यों?
Development में hot reload के साथ modules तेज़ी से देता है, npm imports सुलझाता है, और production के लिए bundle, minify, tree-shake, code split करता है और caching के लिए file names fingerprint करता है।
सारांश
- हर module की एक ज़िम्मेदारी; दूसरों को जो चाहिए वह export।
- Helpers के लिए named exports, मुख्य चीज़ के लिए default; HTML में type="module"।
- npm + package.json + lock file; node_modules कभी commit नहीं।
- Dev/build के लिए Vite; ESLint bugs ढूँढता है, Prettier format करता है।
Day 22: काम के browser APIs – IntersectionObserver, clipboard, share, geolocation, URL parameters और history।
