Description
A preImport
hook can take the place of the async use cases for having an async resolver hook by allowing any async work to be done upfront before triggering the further pipeline steps. For example, loading an import map could be an async operation prior to synchronously using that import map in resolution (which is exactly what the browser does).
Ultimately, the goal would be that by covering these needs, this should allow for a synchronous core resolver which would enable unification with browser resolution.
The initial hook PR would not deprecate the resolver yet, and could be released to get feedback on this first, before following up with a subsequent async resolver deprecation.
There is a basic draft API in nodejs/node#43245, with the following documentation:
preImport(specifier, context)
* `specifier` {string}
* `context` {Object}
* `conditions` {string\[]} Resolution conditions of the current environment,
as defined for the `package.json` imports and exports fields
* `dynamic` {boolean} Whether this import is a dynamic `import()`
* `importAssertions` {Object}
* `parentURL` {string|undefined} The module importing this one, or undefined
if this is the Node.js entry point
The
preImport
hook allows for tracking and asynchronous setup work for every
top-level import operation.
ThepreImport
hook is called for each top-level import operation by the
module loader, both for the host-called imports (ie for the main entry) and for
dynamicimport()
imports. These are distinguished by thedynamic
context.
AllpreImport
hooks for all loaders are run asynchronously in parallel,
and block any further load operations (ie resolve and load) for the module graph
being imported until they all complete successfully.
Multiple import calls to the same import specifier will re-call the hook
multiple times. The first error thrown by thepreImport
hooks will be directly
returned to the specific import operation as the load failure.
export async function preImport (specifier, context) {
if (context.topLevel)
console.log(`Top-level load of ${specifier}`);
else
console.log(`Dynamic import of ${specifier} in ${context.parentURL}`);
}