当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Node.js load(url, context, defaultLoad)用法及代码示例

load(url, context, defaultLoad)

加载程序 API 正在重新设计。这个钩子可能会消失,或者它的签名可能会改变。不要依赖下面说明的 API。

在此 API 的先前版本中,它被拆分为 3 个单独的、现已弃用的钩子(getFormatgetSourcetransformSource)。

load 钩子提供了一种方法来定义自定义方法来确定应如何解释、检索和解析 URL。它还负责验证导入断言。

format 的最终值必须是以下之一:

format说明load 返回的 source 的可接受类型
'builtin'加载 Node.js 内置模块不适用
'commonjs'加载一个 Node.js CommonJS 模块不适用
'json'加载 JSON 文件{ string , ArrayBuffer , TypedArray }
'module'加载一个 ES 模块{ string , ArrayBuffer , TypedArray }
'wasm'加载 WebAssembly 模块{ ArrayBuffer , TypedArray }

source 的值对于类型 'builtin' 被忽略,因为目前无法替换 Node.js 内置(核心)模块的值。 source 的值对于类型 'commonjs' 被忽略,因为 CommonJS 模块加载器没有为 ES 模块加载器提供覆盖 CommonJS module return value 的机制。未来可能会克服这一限制。

警告:ESM load 钩子和来自 CommonJS 模块的命名空间导出不兼容。尝试将它们一起使用将导致导入中的空对象。这可能会在未来得到解决。

这些类型都对应于 ECMAScript 中定义的类。

如果基于文本的格式(即 'json''module' )的源值不是字符串,则使用 util.TextDecoder 将其转换为字符串。

load 钩子提供了一种方法来定义自定义方法来检索 ES 模块说明符的源代码。这将允许加载程序潜在地避免从磁盘读取文件。它还可用于将无法识别的格式映射到受支持的格式,例如 yamlmodule

/**
 * @param {string} url
 * @param {{
    format: string,
  }} context If resolve settled with a `format`, that value is included here.
 * @param {Function} defaultLoad
 * @returns {Promise<{
    format: string,
    source: string | ArrayBuffer | SharedArrayBuffer | Uint8Array,
  }>}
 */
export async function load(url, context, defaultLoad) {
  const { format } = context;
  if (Math.random() > 0.5) { // Some condition.
    /*
      For some or all URLs, do some custom logic for retrieving the source.
      Always return an object of the form {
        format: <string>,
        source: <string|buffer>,
      }.
    */
    return {
      format,
      source: '...',
    };
  }
  // Defer to Node.js for all other URLs.
  return defaultLoad(url, context, defaultLoad);
}

在更高级的场景中,这也可用于将不受支持的源转换为受支持的源(参见下面的Examples)。

相关用法


注:本文由纯净天空筛选整理自nodejs.org大神的英文原创作品 load(url, context, defaultLoad)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。