QA
Senior LevelNode JS

How do you write custom Node.js ESM loaders (--import hook) to transpile TypeScript or mock modules on the fly?

❓ Interview Prompt: Explain `node:module` `register()`, custom loader hooks (`resolve`, `load`), transpiling TypeScript in memory, and module mocking.

Node 20+ provides customizable ESM Module Loaders via 'module.register()':

Loader Hooks:

•
'resolve(specifier, context)': Intercepts and rewrites module path URLs.
•
'load(url, context)': Transpiles file content (e.g. TypeScript to JS) in memory before handing code to V8!

Code Implementation Example

javascript
import { register } from 'node:module';

// Register custom TypeScript ESM loader hook
register('./ts-loader-hook.mjs', import.meta.url);
💡Registering custom ESM module loader hooks in Node 20+.
🎯 Interview Key Takeaway

Use module.register() to build custom ESM loaders for on-the-fly TypeScript compilation and module mocking.

#ESM Loaders#register#TypeScript#Senior
Back to all Node JS Questions→

More Node JS Interview Questions

Beginner LevelNode JS

How does the Node.js Event Loop work? Explain the 6 execution phases (Timers, Pending, Poll, Check, Close).

Beginner LevelNode JS

What does 'Single-Threaded, Event-Driven, Non-Blocking I/O' mean in Node.js?

Beginner LevelNode JS

What is the difference between process.nextTick() and setImmediate()?