Skip to content

vm: support using the default loader to handle dynamic import()#51244

Merged
nodejs-github-bot merged 5 commits intonodejs:mainfrom
joyeecheung:vm-callback-default
Feb 1, 2024
Merged

vm: support using the default loader to handle dynamic import()#51244
nodejs-github-bot merged 5 commits intonodejs:mainfrom
joyeecheung:vm-callback-default

Conversation

@joyeecheung
Copy link
Member

@joyeecheung joyeecheung commented Dec 21, 2023

This patch adds support for using vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER as the
importModuleDynamically option in all vm APIs that take this 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.

const { Script, constants } = require('node:vm'); const { resolve } = require('node:path'); const { writeFileSync } = require('node:fs'); // Write test.js and test.txt to the directory where the current script // being run is located. writeFileSync(resolve(__dirname, 'test.mjs'), 'export const filename = "./test.json";'); writeFileSync(resolve(__dirname, 'test.json'), '{"hello": "world"}'); // Compile a script that loads test.mjs and then test.json // as if the script is placed in the same directory. const script = new Script( `(async function() {  const { filename } = await import('./test.mjs');  return import(filename, { with: { type: 'json' } })  })();`, { filename: resolve(__dirname, 'test-with-default.js'), importModuleDynamically: constants.USE_MAIN_CONTEXT_DEFAULT_LOADER, }); // { default: { hello: 'world' } } script.runInThisContext().then(console.log);

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.

Fixes: #51154

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

author ready PRs that have at least one approval, no pending requests for changes, and a CI started. commit-queue-squash Add this label to instruct the Commit Queue to squash all the PR commits into the first one. lib / src Issues and PRs related to general changes in the lib or src directory. needs-ci PRs that need a full CI run. semver-minor PRs that contain new features and should be released in the next minor version.

7 participants