globalPreload()
¥Stability: 1.0 - Early development
警告:该钩子将在未来版本中删除。改用
initialize
。当 hooks 模块具有initialize
导出时,globalPreload
将被忽略。¥Warning: This hook will be removed in a future version. Use
initialize
instead. When a hooks module has aninitialize
export,globalPreload
will be ignored.
-
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
。这可以作为钩子的参数以及钩子返回的源文本的内部。此功能已移至 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);
});
`;
}