Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
Frontend System Design Roadmap
  1. 1.HTTP/1.1 vs HTTP/2 vs HTTP/3 (QUIC)
  2. 2.TCP and TLS Handshakes: Connection Setup Costs
  3. 3.Browser Network Stack and Connection Pooling
  4. 4.GET vs POST and Idempotency in HTTP
  5. 5.The Critical Rendering Path (CRP)
  6. 6.DOM, CSSOM and the Render Tree
  7. 7.Layout, Paint and Compositing
  8. 8.Reflows and Repaints Explained
  9. 9.Event Loop: Call Stack, Task and Microtask Queues
  10. 10.Async JavaScript: Promises and async/await
  11. 11.Web Workers: Multi-threading in the Browser
  12. 12.Browser Storage: Cookies, Web Storage, IndexedDB
  13. 13.Client-Side Storage: Limits and Security Risks
  14. 14.Choosing the Right Client-Side Storage
  15. 15.HTTP Caching: Cache-Control, ETag, Last-Modified
  16. 16.Browser-Level Caching Mechanisms
  17. 17.Cache Invalidation for Frontend Apps
  18. 18.Structuring a Large Single-Page App
  19. 19.Component-Based Architecture Principles
  20. 20.Props, State and Component Lifecycle
  21. 21.Module Bundling Basics
  22. 22.Core Web Vitals: LCP, INP and CLS
  23. 23.FCP and Time to Interactive (TTI) Explained
  24. 24.Measuring Performance: Lighthouse and WebPageTest
  25. 25.Asset Compression and Minification Basics
  26. 26.What Is a CDN and How Does It Work?
  27. 27.CDN Benefits: Latency, Availability, Offload
  28. 28.CDN Cache Behavior and Invalidation
  29. 29.Global State vs Local Component State
  30. 30.State Patterns: Redux, Zustand and Context
  31. 31.Data Fetching: React Query and SWR
  32. 32.Immutable Data in Frontend State
  33. 33.SSR vs CSR: Rendering Trade-offs
  34. 34.Hydration and Time to First Byte (TTFB)
  35. 35.Static Site Generation (SSG) for Speed and SEO
  36. 36.Incremental Static Regeneration (ISR)
  37. 37.Micro-Frontends: Core Principles
  38. 38.Micro-Frontend Integration Strategies
  39. 39.Communication Between Micro-Frontends
  40. 40.Micro-Frontends: Pros and Cons for Large Teams
  41. 41.Real-Time: Polling, SSE and WebSockets
  42. 42.Real-Time Use Cases: Chat, Alerts, Live Data
  43. 43.Designing a Real-Time Data Flow
  44. 44.Scaling WebSocket Connections
  45. 45.Responsive Images: srcset, sizes and picture
  46. 46.Modern Image Formats: WebP, AVIF, JPEG XL
  47. 47.Lazy Loading Images and Videos
  48. 48.Video Streaming: HLS, DASH, Adaptive Bitrate
  49. 49.REST and GraphQL for Frontend Engineers
  50. 50.Batching, Throttling and Debouncing API Calls
  51. 51.Handling API Errors in the Frontend
  52. 52.Authentication Flows: OAuth and JWT
  53. 53.Global Error Boundaries in React
  54. 54.Error Reporting: Sentry and LogRocket
  55. 55.Graceful Degradation and Fallback UIs
  56. 56.Real User Monitoring (RUM)
  57. 57.CORS: Cross-Origin Resource Sharing
  58. 58.Preventing XSS (Cross-Site Scripting)
  59. 59.CSRF Protection for Frontend Apps
  60. 60.Content Security Policy (CSP)
  61. 61.Storing Auth Tokens: Cookies vs localStorage
  62. 62.PWA Manifest and Installability
  63. 63.Service Workers: Lifecycle and Caching Strategies
  64. 64.Offline Support and Background Sync
  65. 65.Push Notifications for Web Apps
  66. 66.Webpack vs Vite vs Parcel
  67. 67.Code Splitting, Tree Shaking, Asset Optimization
  68. 68.Module Resolution and Hot Module Replacement
  69. 69.Monorepo Tooling: Nx and Lerna
  70. 70.Atomic Design for Component Libraries
  71. 71.Theming and Customization in Design Systems
  72. 72.Accessibility in Component Libraries
  73. 73.Component Library Docs, Testing and Versioning
  74. 74.Publishing and Consuming a Component Library
  75. 75.Full-Text Search: Levenshtein and Fuzzy Matching
  76. 76.Indexing Large Datasets in the Browser
  77. 77.Search Performance: Debouncing and Web Workers
  78. 78.Integrating Backend Search Services
  79. 79.Choosing a Chart Library: D3, Chart.js, Recharts
  80. 80.Rendering Large Datasets: Canvas vs SVG
  81. 81.Interactive, Responsive Data Visualizations
  82. 82.Data Fetching and Aggregation for Dashboards
  83. 83.A/B Test Design and Rollout Strategies
  84. 84.Client-Side vs Server-Side A/B Testing
  85. 85.Feature Flags and Remote Configuration
  86. 86.Experiment Data Collection and Analytics
Frontend System Design Roadmap
68

Frontend System Design · Lesson 68 of 86 · 5 min

Module Resolution and Hot Module Replacement

This topic separates candidates who just use tools from those who understand how they work—a key signal for senior roles.

After this, you'll be able to explain exactly what happens when you save a file in a modern dev environment, why your app state sometimes survives, and why it sometimes doesn't. This is a common line of questioning when discussing build systems or developer experience.

How your import finds its file

Module resolution is the algorithm a bundler or runtime uses to turn an import string like 'react' or '@/utils/math' into an absolute file path. The process is deterministic and follows a clear hierarchy.

  1. Is it a relative or absolute path? Paths starting with ./, ../, or / are resolved relative to the current file or the filesystem root. This is the most straightforward case.
  2. Is it a path alias? Most build systems are configured with aliases (e.g., in tsconfig.json or Webpack's resolve.alias). An import like import Button from '@components/Button' is matched against these aliases first. This is critical for maintainability in large codebases, preventing fragile, deeply nested relative paths.
  3. Is it a bare specifier? For an import like import 'lodash', the resolver begins its search. It looks for a node_modules directory in the current file's directory. If not found, it walks up the directory tree, checking for node_modules at each level until it reaches the root.

This node_modules crawl can be a performance bottleneck in complex monorepos with many dependencies. Tools like pnpm mitigate this with a flattened, symlinked node_modules structure.

In an interview, connect this to system design. When asked to design a large-scale frontend, mention configuring path aliases from the start. It's a small detail that demonstrates foresight about code organization and refactoring pain points. Explain that consistent aliases are essential for monorepo packages to reference each other without relative path hell.

The trap: A common source of build failures is a mismatch between TypeScript path aliases in tsconfig.json and the bundler's alias configuration (e.g., Webpack's resolve.alias). The code type-checks, but the build fails because the bundler can't find the module. Always ensure they are in sync.

The difference between HMR and a page refresh

Hot Module Replacement (HMR) updates modules in a running application without a full reload. This is not the same as live-reload, which just refreshes the page. The key benefit of HMR is state preservation.

When you save a file, the dev server recompiles only the changed module and its direct dependents. It then sends a message to a small HMR runtime client living in your browser, typically over a WebSocket. The client determines if the update can be "hot-swapped." If successful, your application state (component state, Redux store, form inputs) remains intact. If not, it falls back to a full page reload.

This mechanism is what allows you to tweak a component's styles or logic and see the change instantly without being kicked out of the user flow you were testing.

How to control HMR with the module.hot API

While frameworks like React (with Fast Refresh) and Vue handle HMR for components automatically, you sometimes need to manage it manually, especially for modules with side effects. This is done via the module.hot API, exposed by bundlers like Webpack and Vite.

The two most important methods are accept and dispose.

  • module.hot.accept() tells the bundler that this module (and its dependencies) can be safely updated.
  • module.hot.dispose(callback) registers a cleanup function that runs just before the current module instance is discarded.

This is critical for preventing memory leaks. If your module sets up a WebSocket connection, a timer with setInterval, or a global event listener, you must tear it down in the dispose handler. Otherwise, you'll get a new one with every hot update, but the old one will still be running in the background.

// src/dataService.js
let subscribers = [];
let intervalId = null;

function startDataEmitter() {
  // A side effect: a timer that pushes data
  intervalId = setInterval(() => {
    const data = { timestamp: Date.now() };
    subscribers.forEach(sub => sub(data));
  }, 2000);
}

export function subscribe(callback) {
  if (subscribers.length === 0) {
    startDataEmitter();
  }
  subscribers.push(callback);
  return () => {
    subscribers = subscribers.filter(sub => sub !== callback);
    if (subscribers.length === 0) {
      clearInterval(intervalId);
      intervalId = null;
    }
  };
}

// HMR-specific logic
if (import.meta.hot) { // Vite/Webpack 5 API
  import.meta.hot.dispose(() => {
    // Clean up side effects of the OLD module before it's replaced.
    console.log('HMR: Disposing old dataService. Clearing interval.');
    if (intervalId) {
      clearInterval(intervalId);
    }
    // You might also want to transfer state to the new module here.
    // For example: import.meta.hot.data.subscribers = subscribers;
  });

  import.meta.hot.accept(() => {
    // The new module has already been evaluated at this point.
    console.log('HMR: Accepted update for dataService.');
  });
}

In the code above, when you save dataService.js, the dispose function runs, clearing the old setInterval. The new module then runs, and if a subscription is active, it starts a new interval. No memory leaks, no duplicate timers.

Why HMR fails (and what to do about it)

HMR fails and triggers a full reload when an update "bubbles" all the way up the module import graph without being accepted.

When a module is updated, the HMR runtime checks if that module has an accept handler. If not, it checks the parent module that imported it. This continues up the chain. If no module in the chain accepts the update, the runtime gives up and reloads the page.

Here's the HMR update flow:

Common reasons for HMR failure:

  • Changes in modules with global side effects: Modifying a file that injects global CSS or sets up a singleton on window often can't be hot-swapped safely.
  • Updating providers or root-level config: Changing a React Context provider, the Redux store setup, or the root application entry point usually requires a full reset.
  • Code that doesn't use the HMR API: A module with side effects (like the setInterval example) that lacks a dispose handler can lead to an inconsistent state, and some HMR systems will force a reload to be safe.

When HMR fails, open your browser's developer console. The HMR runtime usually logs verbose messages explaining which module changed and why it had to perform a full reload. This is your starting point for debugging.

Try it

In a project using Vite or Create React App, create a new module that uses setInterval to log a message to the console every second. Import and use this module in a component. Now, implement the module.hot.dispose (for Webpack) or import.meta.hot.dispose (for Vite) API to clearInterval on hot updates. Change the log message and save the file. Watch the console to confirm the old interval stops and the new one begins without a page refresh.

Next: Monorepo Tooling: Nx and Lerna.

Lock it in — apply this lesson under interview conditions.

Try a free mock interviewPractice system design problems
Previous

Code Splitting, Tree Shaking, Asset Optimization

Next

Monorepo Tooling: Nx and Lerna