transformSource(source, context, defaultTransformSource)


NODE_OPTIONS='--experimental-loader ./custom-loader.mjs' node x.js

注意:加载器 API 正在重新设计。 这个钩子可能会消失,或者它的签名可能会改变。 不要依赖下面描述的 API。

transformSource 钩子提供了一种在加载源字符串之后但在 Node.js 对其进行任何操作之前修改加载的 ES 模块文件的源代码的方法。

如果此钩子用于将未知的 Node.js 文件类型转换为可执行的 JavaScript,则还需要解析钩子来注册任何未知的 Node.js 文件扩展名。 请参阅下面的转译加载器示例

/**
 * @param {!(string | SharedArrayBuffer | Uint8Array)} source
 * @param {{
 *   format: string,
 *   url: string,
 * }} context
 * @param {Function} defaultTransformSource
 * @returns {Promise<{ source: !(string | SharedArrayBuffer | Uint8Array) }>}
 */
export async function transformSource(source, context, defaultTransformSource) {
  const { url, format } = context;
  if (Math.random() > 0.5) { // 一些条件。
    // 对于部分或全部 URL,做一些修改源的自定义逻辑。
    // 总是返回 {source: <string|buffer>} 形式的对象。
    return {
      source: '...',
    };
  }
  // 对于所有其他来源,请遵循 Node.js。
  return defaultTransformSource(source, context, defaultTransformSource);
}
NODE_OPTIONS='--experimental-loader ./custom-loader.mjs' node x.js

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

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.

/**
 * @param {!(string | SharedArrayBuffer | Uint8Array)} source
 * @param {{
 *   format: string,
 *   url: string,
 * }} context
 * @param {Function} defaultTransformSource
 * @returns {Promise<{ source: !(string | SharedArrayBuffer | Uint8Array) }>}
 */
export async function transformSource(source, context, defaultTransformSource) {
  const { url, format } = context;
  if (Math.random() > 0.5) { // Some condition.
    // For some or all URLs, do some custom logic for modifying the source.
    // Always return an object of the form {source: <string|buffer>}.
    return {
      source: '...',
    };
  }
  // Defer to Node.js for all other sources.
  return defaultTransformSource(source, context, defaultTransformSource);
}