@@ -4,6 +4,48 @@ A user loader that defines a hook might need to reimplement all of Node’s orig
4
4
5
5
These will be added in stages, starting with helpers for the ` resolve ` hook that cover the various steps that Node’s internal ` resolve ` performs.
6
6
7
+ ## Usage
8
+
9
+ The intended usage for these helpers is to eliminate boilerplate within user-defined hooks. For example:
10
+
11
+ ``` js
12
+ import { isBareSpecifier , packageResolve } from ' node:module' ;
13
+ import { readFileSync } from ' node:fs' ;
14
+ import { join } from ' node:path' ;
15
+ import { fileURLToPath , pathToFileURL } from ' node:url' ;
16
+
17
+
18
+ const needsTranspilation = new Set ();
19
+
20
+ export function resolve (specifier , context , next ) {
21
+ if (! isBareSpecifier (specifier)) {
22
+ return next (specifier, context);
23
+ }
24
+
25
+ const pathToPackage = fileURLToPath (packageResolve (specifier, context .parentURL , context .conditions ));
26
+ const pathToPackageJson = join (pathToPackage, ' package.json' );
27
+ const packageMetadata = JSON .parse (readFileSync (pathToPackageJson, ' utf-8' ));
28
+
29
+ if (! packageMetadata .exports && packageMetadata .module ) {
30
+ // If this package has a "module" field but no "exports" field,
31
+ // return the value of "module" and transpile later
32
+ // within a `load` hook
33
+ return {
34
+ url: pathToFileURL (join (pathToPackage, packageMetadata .module ))
35
+ }
36
+ }
37
+ }
38
+
39
+ export async function load (url , context , next ) {
40
+ if (! needsTranspilation .has (url)) {
41
+ return next (url, context);
42
+ }
43
+
44
+ // TODO: Transpile the faux-ESM in the "module" URL
45
+ // and return the transpiled, runnable ESM source
46
+ }
47
+ ```
48
+
7
49
## ` resolve ` helpers
8
50
9
51
### ` packageResolve `
0 commit comments