globalPreload()


加载器 API 正在重新设计。此钩子可能会消失或其签名可能会更改。请不要依赖下面描述的 API。

在该 API 的早期版本中,此钩子被命名为 getGlobalPreloadCode

有时可能需要在应用运行的同一全局作用域中运行一些代码。这个钩子允许返回一个字符串,该字符串将在启动时作为宽松模式脚本运行。

【Sometimes it might be necessary to run some code inside of the same global scope that the application runs in. This hook allows the return of a string that is run as a sloppy-mode script on startup.】

与 CommonJS 封装器的工作方式类似,代码在一个隐式函数作用域中运行。唯一的参数是一个类似 require 的函数,可用于加载内置模块,如 “fs”:getBuiltin(request: string)

【Similar to how CommonJS wrappers work, the code runs in an implicit function scope. The only argument is a require-like function that can be used to load builtins like "fs": getBuiltin(request: string).】

如果代码需要更高级的 require 功能,它必须使用 module.createRequire() 自行构建 require

【If the code needs more advanced require features, it has to construct its own require using module.createRequire().】

export function globalPreload(context) {
  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。这个参数可以作为加载器钩子的参数使用,也可以在钩子返回的源代码中使用。为了正确调用 port.ref()port.unref(),需要小心,以防止进程处于无法正常关闭的状态。

【In order to allow communication between the application and the loader, another argument is provided to the preload code: port. This is available as a parameter to the loader hook and inside of the source text returned by the hook. Some care must be taken in order to properly call port.ref() and port.unref() to prevent a process from being in a state where it won't close normally.】

/**
 * This example has the application context send a message to the loader
 * and sends the message back to the application context
 */
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);
    };
  `;
}