NNext.js 中文网 GitHub

instrumentationClientInject

在用户的 instrumentation-client.{js,ts} 文件之前注入额外的客户端监控模块。

instrumentationClientInject 是一个模块列表,这些模块会在用户的 instrumentation-client.{js,ts} 文件运行之前在客户端导入以产生副作用,且早于 React hydration。

此选项主要面向 next.config.js 插件(例如用于扩展项目配置的 withSentry 或 withAnalytics 等包装器)。它使此类插件能够注入自己的客户端监控模块(包括导航 hook),而无需每个项目都编写或修改 instrumentation-client 文件。应用代码通常应继续直接使用 instrumentation-client.{js,ts} 文件约定。

插件通常会将自己的模块追加到项目已配置的内容之后:

withMyInstrumentation.js
module.exports = function withMyInstrumentation(nextConfig = {}) {
  return {
    ...nextConfig,
    instrumentationClientInject: [
      ...(nextConfig.instrumentationClientInject ?? []),
      'my-instrumentation-package/client',
    ],
  }
}

它也可以直接设置:

next.config.js
/** @type {import('next').NextConfig} */
module.exports = {
  instrumentationClientInject: [
    'my-analytics-package',
    './lib/sentry-client.js',
  ],
}

每个条目是以下之一:

  • 一个纯粹的 npm 包名,从项目的 node_modules 中解析。
  • 一个相对于项目根目录的路径。

执行顺序#

模块按以下顺序在客户端运行:

  1. instrumentationClientInject 中的每个条目,按数组顺序。
  2. 项目的 instrumentation-client.{js,ts} 文件(如果存在)。
  3. React hydration。

路由导航 hook#

每个注入的模块可以选择导出一个 onRouterTransitionStart 函数,其签名与 instrumentation-client 文件约定中记录的函数相同。Next.js 组合成一个单一的 hook,在每次导航时分发给每个导出的 onRouterTransitionStart,按数组顺序调用它们,用户文件中的 hook 最后运行。

lib/sentry-client.js
// 有副作用的设置会在加载时运行。
setupSentry()

export function onRouterTransitionStart(url, navigationType) {
  recordNavigationBreadcrumb(url, navigationType)
}

未导出 onRouterTransitionStart 的模块在导航期间会被跳过。

版本历史#

版本变更
v16.3.0引入了 instrumentationClientInject
Next.js 中文网