From 4f055d2a828838ca8472ea7a18b2905bebb999f0 Mon Sep 17 00:00:00 2001 From: Joyee Cheung Date: Thu, 21 Dec 2023 00:29:26 +0100 Subject: [PATCH] vm: support using the default loader to handle dynamic import() This patch adds support for using `vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER` as `importModuleDynamically` in all APIs that take the option except `vm.SourceTextModule`. This allows users to have a shortcut to support dynamic import() in the compiled code without missing the compilation cache if they don't need customization of the loading process. We emit an experimental warning when the `import()` is actually handled by the default loader through this option instead of requiring `--experimental-vm-modules`. In addition this refactors the documentation for `importModuleDynamically` and adds a dedicated section for it with examples. `vm.SourceTextModule` is not supported in this patch because it needs additional refactoring to handle `initializeImportMeta`, which can be done in a follow-up. --- doc/api/vm.md | 412 +++++++++++++----- lib/internal/modules/cjs/loader.js | 18 +- lib/internal/modules/esm/translators.js | 14 +- lib/internal/modules/esm/utils.js | 71 +-- lib/internal/modules/helpers.js | 35 +- lib/internal/process/pre_execution.js | 26 +- lib/internal/source_map/source_map_cache.js | 8 +- lib/internal/vm.js | 27 +- lib/vm.js | 20 +- src/env_properties.h | 7 +- src/module_wrap.cc | 1 + .../test-vm-main-context-default-loader.js | 138 ++++++ tools/doc/type-parser.mjs | 2 + 13 files changed, 589 insertions(+), 190 deletions(-) create mode 100644 test/es-module/test-vm-main-context-default-loader.js diff --git a/doc/api/vm.md b/doc/api/vm.md index c3a34ea9007dd6..8ebcf6484dc44e 100644 --- a/doc/api/vm.md +++ b/doc/api/vm.md @@ -58,6 +58,11 @@ executed in specific contexts. + +* {Object} + +Returns an object containing commonly used constants for VM operations. + +### `vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER` + + + +> Stability: 1.1 - Active development + +A constant that can be used as the `importModuleDynamically` option to +`vm.Script` and `vm.compileFunction()` so that Node.js uses the default +ESM loader from the main context to load the requested module. + +For detailed information, see +[Support of dynamic `import()` in compilation APIs][]. + ## `vm.createContext([contextObject[, options]])`