[next-intl] request.mjs 中 getRequestConfig 的调用流程解析
使用 next-intl 需要在 next.config.js 中加入如下配置:
import createNextIntlPlugin from 'next-intl/plugin'
const nextConfig = {}
const withNextIntl = createNextIntlPlugin({
requestConfig: './i18n/request.mjs',
})
export default withNextIntl(nextConfig)
createNextIntlPlugin 会创建 next-intl/config 的别名,具体实现如下:
参考:源码链接
// 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/getTranslations → getRequestConfig 执行
执行特点
- 每个请求都会执行一次
- 在 React Server Component 渲染过程中执行
- 可以访问
cookies()、headers()等 Next.js 服务器端 API - 返回的配置会被缓存,供该请求的后续 Server Component 使用
总结
getRequestConfig 通过别名机制隐藏调用过程,这样更容易解耦配置和引用两个步骤。