如何从 Next.js 中的配置访问语言环境值?

How to access locale value from config in Next.js?

我需要从我的 Next.js 应用程序的配置中获取 i18n.defaultLocale。这似乎是一项微不足道的任务,但我找不到任何关于阅读 Next.js 应用程序配置的信息。是否有任何内置对象可供使用,或者我应该只导入由 next.config.js?

导出的对象

不是直接从您的 next.config.js 文件访问值,Next.js 提供了两种访问区域设置信息的方法,具体取决于您需要的位置。

在客户端,从 React 组件,您可以使用 useRouter() 挂钩访问语言环境信息,包括 defaultLocale.

const { defaultLocale, locale, locales } = useRouter()
console.log(defaultLocale)

在服务器上,当使用 getStaticProps/getStaticPaths/getServerSideProps 预呈现页面时,会在传递给这些函数的上下文中提供语言环境信息。

export async function getStaticProps({ defaultLocale, locale, locales }) {
    console.log(defaultLocale)
    // ...
}

getInitialProps 还从其上下文中公开了一个 router 对象,可用于检索语言环境数据。

Page.getInitialProps = async ({ router }) => {
    const { defaultLocale, locale, locales } = router
    console.log(defaultLocale)
    // ...
}