Skip to content

Commit 77c926b

Browse files
tniessendanielleadams
authored andcommitted
doc: fix typo in ESM example
Refs: #37468 PR-URL: #40275 Reviewed-By: Luigi Pinca <luigipinca@gmail.com> Reviewed-By: Derek Lewis <DerekNonGeneric@inf.is> Reviewed-By: Juan José Arboleda <soyjuanarbol@gmail.com> Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com> Reviewed-By: Zijian Liu <lxxyxzj@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com>
1 parent 8cbb2b8 commit 77c926b

File tree

1 file changed

+27
-11
lines changed

1 file changed

+27
-11
lines changed

doc/api/esm.md

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -960,17 +960,33 @@ export function getFormat(url, context, defaultGetFormat) {
960960
return defaultGetFormat(url, context, defaultGetFormat);
961961
}
962962
963-
export function transformSource(source, context, defaultTransformSource) {
964-
const { url, format } = context;
965-
966-
if (extensionsRegex.test(url)) {
967-
return {
968-
source: CoffeeScript.compile(source, { bare: true })
969-
};
970-
}
971-
972-
// Let Node.js handle all other sources.
973-
return defaultTransformSource(source, context, defaultTransformSource);
963+
async function getPackageType(url) {
964+
// `url` is only a file path during the first iteration when passed the
965+
// resolved url from the load() hook
966+
// an actual file path from load() will contain a file extension as it's
967+
// required by the spec
968+
// this simple truthy check for whether `url` contains a file extension will
969+
// work for most projects but does not cover some edge-cases (such as
970+
// extension-less files or a url ending in a trailing space)
971+
const isFilePath = !!extname(url);
972+
// If it is a file path, get the directory it's in
973+
const dir = isFilePath ?
974+
dirname(fileURLToPath(url)) :
975+
url;
976+
// Compose a file path to a package.json in the same directory,
977+
// which may or may not exist
978+
const packagePath = resolvePath(dir, 'package.json');
979+
// Try to read the possibly nonexistent package.json
980+
const type = await readFile(packagePath, { encoding: 'utf8' })
981+
.then((filestring) => JSON.parse(filestring).type)
982+
.catch((err) => {
983+
if (err?.code !== 'ENOENT') console.error(err);
984+
});
985+
// Ff package.json existed and contained a `type` field with a value, voila
986+
if (type) return type;
987+
// Otherwise, (if not at the root) continue checking the next directory up
988+
// If at the root, stop and return false
989+
return dir.length > 1 && getPackageType(resolvePath(dir, '..'));
974990
}
975991
```
976992

0 commit comments

Comments
 (0)