From 39284fcb52422ac2a6061efc60071f7d9d1f51e3 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 | 359 +++++++++++++----- lib/internal/modules/cjs/loader.js | 15 +- lib/internal/modules/esm/translators.js | 14 +- lib/internal/modules/esm/utils.js | 41 +- lib/internal/modules/helpers.js | 29 +- lib/internal/process/pre_execution.js | 22 +- 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 | 170 +++++++++ tools/doc/type-parser.mjs | 2 + 13 files changed, 552 insertions(+), 163 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 7a2c59c867f4a1..4f1837288f1d1c 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 - Experimental + +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]])`