getGlobalPreloadCode()


注意:加载器 API 正在重新设计。 这个钩子可能会消失,或者它的签名可能会改变。 不要依赖下面描述的 API。

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

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

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

/**
 * @returns {string} 在应用程序启动之前运行的代码
 */
export function getGlobalPreloadCode() {
  return `\
globalThis.someInjectedProperty = 42;
console.log('I just set some globals!');

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

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

Note: The loaders API is being redesigned. This hook may disappear or its signature may change. Do not rely on the API described below.

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 sloppy-mode script on startup.

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).

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

/**
 * @returns {string} Code to run before application startup
 */
export function getGlobalPreloadCode() {
  return `\
globalThis.someInjectedProperty = 42;
console.log('I just set some globals!');

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

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