javascript / expert
Snippet
Custom ESM Transformation Hooks
Node.js ESM Loaders allow developers to intercept the module loading lifecycle. By exporting a 'load' or 'resolve' hook, you can transform source code on the fly, implement custom protocols, or handle non-standard file extensions without pre-compilation steps.
snippet.js
1
2
3
4
5
6
7
8
9
// loader.mjsexport async function load(url, context, nextLoad) {if (url.endsWith('.custom')) {const { source } = await nextLoad(url, { ...context, format: 'module' });const transformed = source.toString().replace(/@SECRET/g, '"REDACTED"');return { format: 'module', shortCircuit: true, source: transformed };}return nextLoad(url);}
nodejs
Breakdown
1
export async function load(url, context, nextLoad) {
The hook called by Node.js when a module is being loaded.
2
shortCircuit: true,
Indicates that this hook has handled the request and no further hooks should be called.
3
source: transformed
The modified source code that Node.js will evaluate as a module.