Oasis's Cloud

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

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

作者:oasis


使用 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 的执行,例如:

执行顺序

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

执行特点

总结

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