globalPreload()
版本历史
| 版本 | 变更 |
|---|---|
| v16.17.0 | 添加对链接 globalPreload 钩子的支持。 |
加载程序 API 正在重新设计。这个钩子可能会消失或者它的签名可能会改变。不要依赖下面描述的 API。
\The loaders API is being redesigned. This hook may disappear or its signature may change. Do not rely on the API described below.
在此 API 的先前版本中,此钩子名为
getGlobalPreloadCode。\In a previous version of this API, this hook was named
getGlobalPreloadCode.
-
context<Object> 辅助预加载代码的信息\
context<Object> Information to assist the preload codeport<MessagePort>
-
返回:<string> 应用启动前运行的代码
\Returns: <string> Code to run before application startup
有时可能需要在应用运行所在的同一全局作用域内运行一些代码。此钩子允许返回在启动时作为宽松模式脚本运行的字符串。
\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);
};
`;
}