reactjs - 如何从 api 端点正确加载 next-i18next 中的 i18n 资源?
问题描述
我有一个 nextjs 应用程序,我想使用 i18next 和 next-i18next ( https://github.com/isaachinman/next-i18next ) 对其进行扩展。
默认配置是在 下查找 json 文件./public/locales/{lng}/{ns}.json
,其中 lng 是语言,ns 是命名空间。
然而,我的要求是,这应该从 api 端点提供。我正在努力寻找正确的配置,就像next-i18next
现在忽略我的设置并且没有向我的后端发出任何 xhr 请求一样。
下一个 i18next.config.js:
const HttpApi = require('i18next-http-backend')
module.exports = {
i18n: {
defaultLocale: 'de',
locales: ['en', 'de'],
},
backend: {
referenceLng: 'de',
loadPath: `https://localhost:5001/locales/de/common`,
parse: (data) => {
console.log(data)
return data
}
},
debug: true,
ns: ['common', 'footer', 'second-page'], // the namespaces needs to be listed here, to make sure they got preloaded
serializeConfig: false, // because of the custom use i18next plugin
use: [HttpApi],
}
我在这里不知所措。我究竟做错了什么?
解决方案
最终我把它拼凑在一起。
const I18NextHttpBackend = require('i18next-http-backend')
module.exports = {
i18n: {
defaultLocale: 'de',
locales: ['de'],
backend: {
loadPath: `${process.env.INTERNAL_API_URI}/api/locales/{{lng}}/{{ns}}`
},
},
debug: true,
ns: ["common", "employees", "projects"],
serializeConfig: false,
use: [I18NextHttpBackend]
}
你可能会遇到一个错误,说 You are passing a wrong module! Please check the object you are passing to i18next.use()
. 如果是这种情况,您可以使用以下导入强制 http 后端加载为 commonjs:
const I18NextHttpBackend = require('i18next-http-backend/cjs')
第一个在 webpack 5 上工作,而我不得不在 webpack 4 上使用 cjs 导入。虽然我找不到原因。
在此之后,它一帆风顺:
_app.tsx:
/*i18n */
import { appWithTranslation } from 'next-i18next'
import NextI18nextConfig from '../../next-i18next.config'
const MyApp = ({ Component, pageProps }: AppProps) => {
return (
<>
<MsalProvider instance={msalApp}>
<PageLayout>
<Component {...pageProps} />
</PageLayout>
</MsalProvider>
</>
)
}
export default appWithTranslation(MyApp, NextI18nextConfig)
anypage.tsx:
export const getServerSideProps: GetServerSideProps = async ({ locale }) => {
return {
props: {
...(await serverSideTranslations(locale, ['common', 'employees'])),
// Will be passed to the page component as props
},
};
}
如果您只需要获取一次语言环境,则在构建期间,您可以getStaticProps
改用 - 这取决于您。
推荐阅读
- tensorflow - 为什么我的 MNSIT 数字项目的每个预测都是错误的?
- c - 在没有 C/Linux 中的磁盘 I/O 的情况下在 linux 上的自己的进程上读取调试/静态符号?
- spring - 使用 Spring Security 对用户进行身份验证
- c# - 如何仅从 win 表单中的文本文件中提取数字?
- date - ssh连接的生命周期
- dns - 对网络解决方案的担忧 合并了不当的商业行为
- xpath - 使用 XPath 获取“位置:”背后的内容
- powershell - cmd.exe 抛出错误“& 在这个时候是意外的。”
- python-3.x - 如何在多处理中的两个单独脚本之间传输数据?
- java - 可调用布尔值的语法是什么