globalPreload()


稳定性: 1.0 - 早期开发

警告: 此钩子将在未来版本中被移除。请使用 initialize 代替。当 hooks 模块包含 initialize 导出时,globalPreload 将被忽略。

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

🌐 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。这个参数可以作为钩子的参数使用,并且可以在钩子返回的源代码中使用。此功能已被移至 initialize 钩子。

🌐 Another argument is provided to the preload code: port. This is available as a parameter to the hook and inside of the source text returned by the hook. This functionality has been moved to the initialize hook.

必须小心,以正确调用 port.ref()port.unref(),防止进程处于无法正常关闭的状态。

🌐 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 hook
 * and sends the message back to the application context
 */
export function globalPreload({ port }) {
  port.on('message', (msg) => {
    port.postMessage(msg);
  });
  return `\
    port.postMessage('console.log("I went to the hook and back");');
    port.on('message', (msg) => {
      eval(msg);
    });
  `;
}