From 6370b4df68dabe4975d2ea5d1883803db5176f60 Mon Sep 17 00:00:00 2001 From: Antoine du Hamel Date: Tue, 18 Jan 2022 19:13:44 +0100 Subject: [PATCH] doc: recommend package exports instead of requiring folders PR-URL: https://github.com/nodejs/node/pull/41381 Reviewed-By: James M Snell Reviewed-By: Geoffrey Booth --- doc/api/modules.md | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/doc/api/modules.md b/doc/api/modules.md index ce8b1d5f123e23..0adca6de8dc50f 100644 --- a/doc/api/modules.md +++ b/doc/api/modules.md @@ -436,8 +436,8 @@ If the given path does not exist, `require()` will throw an [`Error`][] with its -It is convenient to organize programs and libraries into self-contained -directories, and then provide a single entry point to those directories. +> Stability: 3 - Legacy: Use [subpath exports][] or [subpath imports][] instead. + There are three ways in which a folder may be passed to `require()` as an argument. @@ -454,8 +454,6 @@ If this was in a folder at `./some-library`, then `require('./some-library')` would attempt to load `./some-library/lib/some-library.js`. -This is the extent of the awareness of `package.json` files within Node.js. - If there is no [`package.json`][] file present in the directory, or if the [`"main"`][] entry is missing or cannot be resolved, then Node.js will attempt to load an `index.js` or `index.node` file out of that @@ -472,6 +470,11 @@ with the default error: Error: Cannot find module 'some-library' ``` +In all three above cases, an `import('./some-library')` call would result in a +[`ERR_UNSUPPORTED_DIR_IMPORT`][] error. Using package [subpath exports][] or +[subpath imports][] can provide the same containment organization benefits as +folders as modules, and work for both `require` and `import`. + ## Loading from `node_modules` folders @@ -1080,6 +1083,7 @@ This section was moved to [`"main"`]: packages.md#main [`"type"`]: packages.md#type [`ERR_REQUIRE_ESM`]: errors.md#err_require_esm +[`ERR_UNSUPPORTED_DIR_IMPORT`]: errors.md#err_unsupported_dir_import [`Error`]: errors.md#class-error [`__dirname`]: #__dirname [`__filename`]: #__filename @@ -1094,3 +1098,5 @@ This section was moved to [exports shortcut]: #exports-shortcut [module resolution]: #all-together [native addons]: addons.md +[subpath exports]: packages.md#subpath-exports +[subpath imports]: packages.md#subpath-imports