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


Node.js globalPreload()用法及代码示例

globalPreload()

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

在此 API 的先前版本中,此钩子被命名为 getGlobalPreloadCode

有时可能需要在应用程序运行所在的同一全局范围内运行一些代码。此钩子允许返回一个字符串,该字符串在启动时作为 sloppy-mode 脚本运行。

与CommonJS 包装器的工作方式类似,代码在隐式函数范围内运行。唯一的参数是一个类似于 require 的函数,可用于加载像 "fs": getBuiltin(request: string) 这样的内置函数。

如果代码需要更高级的 require 函数,则必须使用 module.createRequire() 构建自己的 require

/**
 * @param {{
     port: MessagePort,
   }} utilities Things that preload code might find useful
 * @returns {string} Code to run before application startup
 */
export function globalPreload(utilities) {
  return `\
globalThis.someInjectedProperty = 42;
console.log('I just set some globals!');

const { createRequire } = getBuiltin('module');
const { cwd } = getBuiltin('process');

const require = createRequire(cwd() + '/<preload>');
// [...]
`;
}

为了允许应用程序和加载程序之间进行通信,预加载代码提供了另一个参数:port。这可作为 loader 钩子的参数和钩子返回的源文本内部使用。必须注意正确调用 port.ref() port.unref() 以防止进程处于无法正常关闭的状态。

/**
 * This example has the application context send a message to the loader
 * and sends the message back to the application context
 * @param {{
     port: MessagePort,
   }} utilities Things that preload code might find useful
 * @returns {string} Code to run before application startup
 */
export function globalPreload({ port }) {
  port.onmessage = (evt) => {
    port.postMessage(evt.data);
  };
  return `\
    port.postMessage('console.log("I went to the Loader and back");');
    port.onmessage = (evt) => {
      eval(evt.data);
    };
  `;
}

相关用法


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