Why does node_modules weigh more than the entire universe? 🤔 If you have ever checked the size of node_modules and wondered why it can reach hundreds of megabytes or even gigabytes while your source code is tiny, you are not alone. This is one of the most common realities in the JavaScript ecosystem. Here is why it happens, explained with simple analogies: 1️⃣ The Matryoshka Doll of Transitive Dependencies 🔹 Imagine buying only flour for a cake, but the package arrives with an entire mini-bakery: sugar, yeast, and recipes for ten other items, each containing their own ingredients. 🔹 That is how npm works. One library pulls dozens or hundreds of transitive dependencies, creating a deeply nested tree inside node_modules. 2️⃣ JavaScript Ships the Full Recipe Book, Not the Finished Cake 🔹 Unlike compiled languages such as Go or Rust that deliver compact binaries, Node.js requires the original source code for Just-In-Time compilation. 🔹 Most packages therefore include not only JavaScript files, but also TypeScript definitions, tests, documentation, polyfills, multiple module formats, and examples. It is like receiving the complete cookbook and all utensils with every single ingredient. 3️⃣ The Duplicate Editions Problem 🔹 Different parts of your project may require slightly different versions of the same library. Semantic versioning rules force npm to install separate copies in different folders, leading to significant duplication. 4️⃣ The Culture of Micro-Packages 🔹 The ecosystem favors many small, single-purpose packages. This modularity multiplies the total number of entries in node_modules. In summary, the large size of node_modules results from deliberate design choices: complete dependency isolation, delivery of full source code, and a preference for tiny reusable modules. The good news is that tools like pnpm use a global store to deduplicate packages, often reducing size by 70 to 90 percent. You can also review your package.json and prune unnecessary dependencies. Have you measured your node_modules recently? What is the largest size you have seen? Share your experiences below. #NodeJS #TypeScript #JavaScript #WebDevelopment #SoftwareEngineering
Why Node Modules Weighs More Than the Universe
More Relevant Posts
-
Why is my code running "out of order"? (Eager vs. Lazy Evaluation) Ever passed a function as an argument and wondered why it executed before the function it was passed into? Look at this common "gotcha": javascript const main = (fn) => { console.log("start"); fn(); console.log("end"); }; const createLogger = (msg) => { console.log("start logger"); return () => console.log(msg); }; // ❌ Unexpected Order: "start logger" -> "start" -> "success" -> "end" main(createLogger("success")); Use code with caution. What’s happening? This is Eager Evaluation. In JavaScript, arguments are evaluated immediately before the outer function runs. Because we used parentheses () on createLogger, JS executes it first to find out what value to give to main. It’s like cooking a 5-course meal before your guests even knock on the door! 🥘 The Fix: Lazy Evaluation 💤 If we want main to control the timing, we need to wrap our logic in a "thunk" (a wrapper function). This tells JS: "Don't run this yet; run it only when I call it." javascript // ✅ Correct Order: "start" -> "start logger" -> "success" -> "end" main(() => createLogger("success")()); Use code with caution. Why does this matter in Node.js? Understanding this distinction is huge for: ✅ Middleware: Deciding when a request starts/ends. ✅ Performance: Avoiding expensive calculations unless they are actually needed. ✅ Closures: Controlling scope and execution timing. Stop executing, start referencing! 🚀 #JavaScript #WebDevelopment #NodeJS #CodingTips #SoftwareEngineering
To view or add a comment, sign in
-
-
JavaScript in 2026: The Dev Update You Didn't Know You Needed ECMAScript continues to evolve, and this year's updates are particularly noteworthy for JavaScript developers. Here’s a comprehensive overview of what’s new, what’s on the horizon, and why it matters. 1. Temporal API — The Biggest JS Feature in Years (ES2026) Date handling in JavaScript has faced challenges since 1995. With the Temporal API, that’s changing. const now = Temporal.Now.zonedDateTimeISO("Asia/Kolkata"); console.log(now.toLocaleString()); // Correct. Always. 2. using keyword — Automatic Resource Cleanup (ES2026) This feature simplifies resource management in asynchronous functions. async function saveData() { await using file = new FileHandle("output.txt"); await file.write("hello"); // file auto-closed here, even on error } No more worries about forgetting to close database connections or file handles. The runtime ensures cleanup when the variable goes out of scope, which is a significant improvement for server-side Node.js development. 3. Iterator Helpers — Lazy Evaluation (ES2025) This update enhances efficiency by allowing lazy evaluation without creating extra arrays. // Old way: creates 3 new arrays array.map(x => x*2).filter(x => x>10).slice(0, 3); // New way: zero extra arrays, stops after 3 Iterator.from(array).map(x => x*2).filter(x => x>10).take(3).toArray(); This feature works seamlessly with Sets, Maps, Generators, and any iterable, improving performance and memory usage. Additional updates include: - Array.fromAsync() — Collect async generator results into an array effortlessly - Iterator.concat() — Lazily iterate across multiple pages/sources - Error.isError() — Reliably detect real Error #JavaScript #ECMAScript2026 #WebDevelopment #TypeScript #FrontendDev #NodeJS #Programming #SoftwareEngineering #TechNews #CodingLife
To view or add a comment, sign in
-
-
I've been writing JavaScript for years. And for years, I thought TypeScript was just extra work. I was wrong. Completely wrong. After switching to TypeScript full-time, my debugging time dropped by almost 40%. My code reviews became faster. Onboarding new devs became easier. And I stopped getting 3am calls about production bugs. Here's everything I wish someone had taught me before making the switch What is TypeScript, really? TypeScript is JavaScript - but with a superpower: a type system. It's a superset of JavaScript, which means every valid JS file is already valid TypeScript. You don't relearn the language. You extend it. TypeScript adds: - Static types (string, number, boolean, custom types) - Interfaces and type aliases - Enums - Generics - Type inference (TS is smart enough to guess types) - Compile-time error checking The TypeScript compiler (tsc) transpiles your .ts files back into plain JavaScript - so browsers and Node.js run it exactly the same. You write safer code. The machine handles the rest. Why JavaScript alone isn't enough anymore in Modern Web Apps JavaScript was built in 10 days in 1995. It was designed for tiny scripts - not 100,000-line enterprise apps, not distributed teams of 50 engineers, not systems that handle millions of users. In JS, this is perfectly valid code: function add(a, b) { return a + b; } add("5", 10); // Returns "510", not 15 No error. No warning. Just wrong behavior at runtime. In TypeScript: function add(a: number, b: number): number { return a + b; } add("5", 10); // ERROR at compile time - caught before it ships This is the core value of TypeScript: it moves bugs from runtime (when users feel it) to compile time (when only you see it).
To view or add a comment, sign in
-
🚨 JavaScript Gotcha: Objects as Keys?! Take a look at this 👇 const a = {}; const b = { key: 'b' }; const c = { key: 'c' }; a[b] = 123; a[c] = 456; console.log(a[b]); // ❓ 👉 What would you expect? 123 or 456? 💡 Actual Output: 456 🤯 Why does this happen? In JavaScript, object keys are always strings or symbols. So when you use an object as a key: a[b] → a["[object Object]"] a[c] → a["[object Object]"] Both b and c are converted into the same string: "[object Object]" ⚠️ That means: a[b] = 123 sets " [object Object] " → 123 a[c] = 456 overwrites it → 456 So finally: console.log(a[b]); // 456 🧠 Key Takeaways ✅ JavaScript implicitly stringifies object keys ✅ Different objects can collide into the same key ❌ Using objects as keys in plain objects is unsafe 🔥 Pro Tip If you want to use objects as keys, use a Map instead: const map = new Map(); map.set(b, 123); map.set(c, 456); console.log(map.get(b)); // 123 ✅ ✔️ Map preserves object identity ✔️ No unexpected overwrites 💬 Final Thought JavaScript often hides complexity behind simplicity. Understanding these small quirks is what separates a developer from an expert. #JavaScript #WebDevelopment #FrontendDevelopment #Programming #Coding #JavaScriptTips #JSConfusingParts #DevelopersLife #CodeNewbie #LearnToCode #SoftwareEngineering #TechTips #CodeQuality #CleanCode #100DaysOfCode #ProgrammingTips #DevCommunity #CodeChallenge #Debugging #JavaScriptDeveloper #MERNStack #FullStackDeveloper #ReactJS #NodeJS #WebDevTips #CodingLife
To view or add a comment, sign in
-
-
TypeScript enums are problematic. Here's what senior developers use instead. Enums look useful. They feel organised. But they introduce real problems in TypeScript projects. The problems with enums: ts// Numeric enums have dangerous reverse mappings enum Direction { Up, Down, Left, Right } Direction[0] // 'Up' — this exists at runtime and causes confusion // Enums are not just a type — they generate JavaScript code // That means your bundle is larger than it needs to be // Const enums cause issues with babel and SWC compilers const enum Status { Active, Inactive } // Can break in certain build configurations What to use instead: Option 1 — Union types (best for most cases) tstype Direction = 'up' | 'down' | 'left' | 'right' // Autocomplete works perfectly // No JavaScript generated // Fully type-safe Option 2 — As const objects (best when you need runtime access) tsconst Status = { ACTIVE: 'active', INACTIVE: 'inactive', PENDING: 'pending', } as const type Status = typeof Status[keyof typeof Status] // Type: 'active' | 'inactive' | 'pending' // You can still do: Status.ACTIVE // 'active' — runtime access works Object.values(Status) // ['active', 'inactive', 'pending'] Why as const objects win: → No extra JavaScript generated → Runtime access when you need it → Works with every build tool → Type is derived automatically → Readable, familiar object syntax Union types for simple cases. as const objects when you need runtime access. Enums — almost never. Were you using enums? What are you switching to? 👇 #TypeScript #JavaScript #FrontendDevelopment #ReactJS #WebDevelopment #CleanCode #SoftwareEngineering
To view or add a comment, sign in
-
-
#Day21 JavaScript just got a whole lot more interesting. Up until now, everything I wrote lived in the browser. Today I started working with Node.js and the fs module and for the first time, my code started talking to my computer directly. Three things clicked today: => Reading a file: "fs.readFile" opens a file sitting on your computer and prints its contents. That's it. No browser, no UI, just my code and my file system having a conversation. => Writing a file: "fs.writeFile" creates a brand new file and puts text inside it. If the file doesn't exist yet, Node creates it for you. One line of code does what used to feel like a whole process. => Appending to a file: "fs.appendFile" adds new content to an existing file without deleting what's already there. It runs after the file is created because in Node, async operations happen in sequence through callbacks. => process.on('uncaughtException'): Ending today with "process.on", this is a safety net. Instead of your program crashing with no explanation, it catches the error, tells you what went wrong, and shuts down cleanly. JavaScript isn't just a browser language. With Node.js, you can read files, write files, manage your system, and build backends all with the same language you already know. Same language. Bigger world. #NodeJS #JavaScript #M4ACELearningChallenge #BackendDevelopment #LearningToCode #WebDevelopment
To view or add a comment, sign in
-
-
Small JavaScript bugs keep escaping to production and breaking critical user flows. Debugging inconsistent runtime behavior steals time from feature delivery. ────────────────────────────── Understanding Type Declaration Files (.d.ts) Ever wondered how to make TypeScript work seamlessly with JavaScript libraries? Let's dive into .d.ts files! #typescript #javascript #development #typedeclaration ────────────────────────────── Core Concept Type declaration files, or .d.ts files, are crucial when working with TypeScript and JavaScript libraries. Have you ever faced issues with type safety while using a library? These files help bridge that gap! Key Rules • Always create a .d.ts file for any JavaScript library that lacks TypeScript support. • Use declare module to define the types of the library's exports. • Keep your declarations organized and maintainable for future updates. 💡 Try This declare module 'my-library' { export function myFunction(param: string): number; } ❓ Quick Quiz Q: What is the main purpose of a .d.ts file? A: To provide TypeScript type information for JavaScript libraries. 🔑 Key Takeaway Type declaration files enhance type safety and improve your TypeScript experience with external libraries!
To view or add a comment, sign in
-
I used to work on a JavaScript codebase where… Every file looked like this 👇Wrapped inside a self-invoking function (IIFE). And honestly…It didn’t make sense to me at first. Why are we doing this? Then I started asking basic questions: 👉 Why do we even split code into multiple files? At a high level → separation of concerns + reusability. We write logic in one file → use it in another.That’s basically what a module system does in any language. Then the next question hit me: 👉 What does IIFE have to do with modules? Here’s the catch: JavaScript initially didn’t have a module system. No imports. No exports. So what happens? 👉 Everything runs in the global scope. Which means: My variables = global Your variables = global Third-party library variables = also global Now imagine same variable names… 💥 Collision. So how did developers deal with this? 👉 Using functions. Because functions in JavaScript create their own scope. So the idea became: Wrap everything inside a function→ invoke it immediately→ expose only what’s needed --> return statement const module = (() => { const p1 = () => {} const p2 = [] const exports = { x1: () => {}, x2: [] } return exports })() Now think about it: 👉 p1 and p2 → private👉 x1 and x2 → public Nothing leaks into global scope. That’s when it clicked for me. This is basically a manual module system. Before:→ CommonJS→ ES Modules Funny thing is… Today we just write: export const x1 = () => {} …but back then, people had to build this behavior themselves. It is not about how things work today but why they exist in the first place. BTW this pattern is called 🫴Revealing Module Pattern.👈 #JavaScript #WebDevelopment #CleanCode #DeveloperJourney #Coding #FrontendDevelopment
To view or add a comment, sign in
-
You add TypeScript to the project. Half the types are any. You basically wrote JavaScript with some extra syntax. TypeScript doesn't make your code safer. You do. And using any turns off the whole tool. Here's what most people miss: any doesn't stay where you put it. It spreads. function getUser(id: string): any { return api.fetch("/users/" + id); } const user = getUser("123"); const name = user.name; const upper = name.toUpperCase(); Every variable in this chain is any. No autocomplete, no safe changes, no errors caught before release. One any at the start shuts down the whole process. This is type erosion. It acts like tech debt — hidden until it causes problems. Before you type any, ask yourself two questions. First question: Do I really not know the type? If the data comes from an API — describe its structure. A partial type is much better than any. Second question: Am I just avoiding a type error? The compiler warns you, and you ignore it. That's not a fix. It's just @ts-ignore with extra steps. Use unknown instead. It means "I don't know" but makes you check before using it. any trusts without question. unknown requires proof. If your code has more than 5% any, you're not really using TypeScript. You're just adding decorations to JavaScript. Run npx type-coverage. Look at the number. Then decide. any is not a type. It's a surrender. #TypeScript #Frontend #JavaScript #WebDev #SoftwareEngineering #CodeQuality
To view or add a comment, sign in
-
-
JavaScript is easy. Until it isn't. 😅 Every developer has been there. You're confident. Your code looks clean. You hit run. And then: " Cannot read properties of undefined (reading 'map') " The classic JavaScript wall. Here are 7 JavaScript mistakes I see developers make constantly and how to fix them: 1. Not understanding async/await ⚡ → Wrong: | const data = fetch('https://lnkd.in/dMDBzbsK'); console.log(data); // Promise {pending} | → Right: | const data = await fetch('https://lnkd.in/dMDBzbsK'); | 2. Using var instead of let/const → var is function scoped and causes weird bugs → Always use const by default. let when you need to reassign. Never var. 3. == instead of === → 0 == "0" is true in JavaScript 😱 → Always use === for comparisons. Always. 4. Mutating state directly in React → Wrong: user.name = "Shoaib" → Right: setUser({...user, name: "Shoaib"}) 5. Forgetting to handle errors in async functions → Always wrap await calls in try/catch → Silent failures are the hardest bugs to track down 6. Not cleaning up useEffect in React → Memory leaks are real → Always return a cleanup function when subscribing to events 7. Treating arrays and objects as primitives → [] === [] is false in JavaScript → Reference types don't compare like numbers — learn this early JavaScript rewards the developers who understand its quirks. 💡 Which of these caught YOU off guard when you first learned it? 👇 #JavaScript #WebDevelopment #Frontend #FullStackDeveloper #React #Programming #CodingTips #Developer #Tech #Pakistan #LearnToCode #JS #SoftwareEngineering #100DaysOfCode #PakistaniDeveloper
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development