0 day streak
javascript / expert
Snippet

Custom ESM Loaders for Runtime Module Instrumentation

Node.js allows customizing the ES module resolution and loading process via loader hooks. This enables on-the-fly transformations (like TypeScript compilation) or security sandboxing by intercepting every 'import' statement in the application.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
// loader.mjs
export async function load(url, context, nextLoad) {
const result = await nextLoad(url, context);
if (url.endsWith('.ts')) {
return {
format: 'module',
shortCircuit: true,
source: transformCode(result.source)
};
}
return result;
}
nodejs
Breakdown
1
export async function load(url, context, nextLoad)
The hook called by Node.js whenever a module needs to be loaded into the source.
2
const result = await nextLoad(url, context);
Calls the default loader or the next hook in the chain to get the raw source.
3
shortCircuit: true,
Informs Node.js that this hook has handled the request and no further hooks are needed.
4
source: transformCode(result.source)
Applies custom logic to the source code before it is parsed by V8.