Note: The loaders API is being redesigned. This hook may disappear or its signature may change. Do not rely on the API described below.

    • source {string|SharedArrayBuffer|Uint8Array}
    • context {Object}
      • format {string}
      • url {string}
    • Returns: {Object}
      • source {string|SharedArrayBuffer|Uint8Array}

    The transformSource hook provides a way to modify the source code of a loaded ES module file after the source string has been loaded but before Node.js has done anything with it.

    If this hook is used to convert unknown-to-Node.js file types into executable JavaScript, a resolve hook is also necessary in order to register any unknown-to-Node.js file extensions. See the [transpiler loader example][] below.

    1. /**
    2. * @param {!(string | SharedArrayBuffer | Uint8Array)} source
    3. * @param {{
    4. * format: string,
    5. * url: string,
    6. * }} context
    7. * @param {Function} defaultTransformSource
    8. * @returns {Promise<{ source: !(string | SharedArrayBuffer | Uint8Array) }>}
    9. */
    10. export async function transformSource(source, context, defaultTransformSource) {
    11. const { url, format } = context;
    12. if (Math.random() > 0.5) { // Some condition.
    13. // For some or all URLs, do some custom logic for modifying the source.
    14. // Always return an object of the form {source: <string|buffer>}.
    15. return {
    16. source: '...',
    17. };
    18. }
    19. // Defer to Node.js for all other sources.
    20. return defaultTransformSource(source, context, defaultTransformSource);
    21. }