resolve(specifier, context, defaultResolve)
resolve
钩子返回给定模块说明符和父 URL 的解析文件 URL,以及可选的格式(例如 'module'
)作为对 load
钩子的提示。
如果指定了格式,则 load
钩子最终负责提供最终的 format
值(可以随意忽略 resolve
提供的提示);如果 resolve
提供了 format
,则需要自定义 load
钩子,即使只是通过 Node.js 默认 load
钩子的值。
The loaders API is being redesigned. This hook may disappear or its signature may change. Do not rely on the API described below.
specifier
<string>context
<Object>conditions
<string[]>importAssertions
<Object>parentURL
<string> | <undefined>
defaultResolve
<Function> The Node.js default resolver.- Returns: <Object>
format
<string> | <null> | <undefined>'builtin' | 'commonjs' | 'json' | 'module' | 'wasm'
url
<string> The absolute url to the import target (such asfile://…
)
The resolve
hook returns the resolved file URL for a given module specifier
and parent URL, and optionally its format (such as 'module'
) as a hint to the
load
hook. If a format is specified, the load
hook is ultimately responsible
for providing the final format
value (and it is free to ignore the hint
provided by resolve
); if resolve
provides a format
, a custom load
hook is required even if only to pass the value to the Node.js default load
hook.
The module specifier is the string in an import
statement or
import()
expression, and the parent URL is the URL of the module that imported
this one, or undefined
if this is the main entry point for the application.
The conditions
property in context
is an array of conditions for
package exports conditions that apply to this resolution
request. They can be used for looking up conditional mappings elsewhere or to
modify the list when calling the default resolution logic.
The current package exports conditions are always in
the context.conditions
array passed into the hook. To guarantee default
Node.js module specifier resolution behavior when calling defaultResolve
, the
context.conditions
array passed to it must include all elements of the
context.conditions
array originally passed into the resolve
hook.
/**
* @param {string} specifier
* @param {{
* conditions: string[],
* parentURL: string | undefined,
* }} context
* @param {Function} defaultResolve
* @returns {Promise<{ url: string }>}
*/
export async function resolve(specifier, context, defaultResolve) {
const { parentURL = null } = context;
if (Math.random() > 0.5) { // Some condition.
// For some or all specifiers, do some custom logic for resolving.
// Always return an object of the form {url: <string>}.
return {
url: parentURL ?
new URL(specifier, parentURL).href :
new URL(specifier).href,
};
}
if (Math.random() < 0.5) { // Another condition.
// When calling `defaultResolve`, the arguments can be modified. In this
// case it's adding another value for matching conditional exports.
return defaultResolve(specifier, {
...context,
conditions: [...context.conditions, 'another-condition'],
});
}
// Defer to Node.js for all other specifiers.
return defaultResolve(specifier, context, defaultResolve);
}