From 4c508269cd897c6a700dd923117db712f4f3e4f2 Mon Sep 17 00:00:00 2001 From: Joyee Cheung Date: Thu, 1 Feb 2024 12:45:42 +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. PR-URL: https://github.com/nodejs/node/pull/51244 Fixes: https://github.com/nodejs/node/issues/51154 Reviewed-By: Antoine du Hamel Reviewed-By: Chengzhong Wu --- doc/api/vm.md | 416 +++++++++++++----- .../bootstrap/switches/is_main_thread.js | 1 - 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 | 142 ++++++ test/parallel/test-bootstrap-modules.js | 1 - tools/doc/type-parser.mjs | 2 + 15 files changed, 596 insertions(+), 193 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 85e5d5ac30d309..c6f9d3a0e29645 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]])`