Note: 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[]}
      • parentURL {string}
    • defaultResolve {Function}
    • Returns: {Object}
      • url {string}

    The resolve hook returns the resolved file URL for a given module specifier and parent URL. 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 on the context is an array of conditions for [Conditional exports][] 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][Conditional Exports] 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.

    1. /**
    2. * @param {string} specifier
    3. * @param {{
    4. * conditions: !Array<string>,
    5. * parentURL: !(string | undefined),
    6. * }} context
    7. * @param {Function} defaultResolve
    8. * @returns {Promise<{ url: string }>}
    9. */
    10. export async function resolve(specifier, context, defaultResolve) {
    11. const { parentURL = null } = context;
    12. if (Math.random() > 0.5) { // Some condition.
    13. // For some or all specifiers, do some custom logic for resolving.
    14. // Always return an object of the form {url: <string>}.
    15. return {
    16. url: parentURL ?
    17. new URL(specifier, parentURL).href :
    18. new URL(specifier).href,
    19. };
    20. }
    21. if (Math.random() < 0.5) { // Another condition.
    22. // When calling `defaultResolve`, the arguments can be modified. In this
    23. // case it's adding another value for matching conditional exports.
    24. return defaultResolve(specifier, {
    25. ...context,
    26. conditions: [...context.conditions, 'another-condition'],
    27. });
    28. }
    29. // Defer to Node.js for all other specifiers.
    30. return defaultResolve(specifier, context, defaultResolve);
    31. }