From 09dad11f8e4433e49fcec5f304c9b86b461a9b99 Mon Sep 17 00:00:00 2001 From: Jan Krems Date: Mon, 19 Aug 2019 20:59:25 -0700 Subject: [PATCH] module: resolve self-references Adds the ability to `import` or `require` a package from within its own source code. This allows tests and examples to be written using the package name, making them easier to reuse by consumers of the package. Assuming the `name` field in `package.json` is set to `my-pkg`, its test could use `require('my-pkg')` or `import 'my-pkg'` even if there's no `node_modules/my-pkg` while testing the package itself. An important difference between this and relative specifiers like `require('../')` is that self-references use the public interface of the package as defined in the `exports` field while relative specifiers don't. This behavior is guarded by a new experimental flag (`--experimental-resolve-self`). --- doc/api/cli.md | 9 + doc/api/esm.md | 28 ++- doc/api/modules.md | 12 +- lib/internal/modules/cjs/loader.js | 166 ++++++++++++++---- src/env.h | 3 + src/module_wrap.cc | 79 +++++++++ src/node_options.cc | 4 + src/node_options.h | 1 + test/es-module/test-esm-exports.mjs | 21 ++- .../node_modules/pkgexports/lib/hole.js | 10 ++ .../node_modules/pkgexports/not-exported.js | 3 + .../node_modules/pkgexports/package.json | 2 + 12 files changed, 294 insertions(+), 44 deletions(-) create mode 100644 test/fixtures/node_modules/pkgexports/lib/hole.js create mode 100644 test/fixtures/node_modules/pkgexports/not-exported.js diff --git a/doc/api/cli.md b/doc/api/cli.md index 7769b0219417b4..69e9e52a629c8e 100644 --- a/doc/api/cli.md +++ b/doc/api/cli.md @@ -196,6 +196,14 @@ added: v11.8.0 Enable experimental diagnostic report feature. +### `--experimental-resolve-self` + + +Enable experimental support for a package using `require` or `import` to load +itself. + ### `--experimental-vm-modules`