Oasis's Cloud

一个人的首要责任,就是要有雄心。雄心是一种高尚的激情,它可以采取多种合理的形式。
—— 《一个数学家的辩白》

[next-intl] request.mjs 中 getRequestConfig 的调用流程解析

作者:oasis


使用 next-intl 需要在 next.config.js 中加入如下配置:

js
import createNextIntlPlugin from 'next-intl/plugin'
const nextConfig = {}

const withNextIntl = createNextIntlPlugin({
    requestConfig: './i18n/request.mjs',
})

export default withNextIntl(nextConfig)

createNextIntlPlugin 会创建 next-intl/config 的别名,具体实现如下:

参考:源码链接

js
// Assign alias for `next-intl/config`
const resolveAlias = {
    // Turbo aliases don't work with absolute
    // paths (see error handling above)
    'next-intl/config': resolveI18nPath(pluginConfig.requestConfig)
};

当 Server Component 调用 next-intl 的服务器端函数时,会触发 getRequestConfig 的执行,例如:

  • getMessages()
  • getTranslations()
  • getFormatter()

执行顺序

请求到达 → Middleware 处理 → Server Component 渲染 → 调用 getMessages/getTranslationsgetRequestConfig 执行

执行特点

  • 每个请求都会执行一次
  • 在 React Server Component 渲染过程中执行
  • 可以访问 cookies()headers() 等 Next.js 服务器端 API
  • 返回的配置会被缓存,供该请求的后续 Server Component 使用

总结

getRequestConfig 通过别名机制隐藏调用过程,这样更容易解耦配置和引用两个步骤。