微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何从 api 端点正确加载 next-i18next 中的 i18n 资源?

如何解决如何从 api 端点正确加载 next-i18next 中的 i18n 资源?

我有一个 nextjs 应用程序,我想使用 i18next 和 next-i18next (https://github.com/isaachinman/next-i18next) 对其进行扩展。

认配置是在 ./public/locales/{lng}/{ns}.json 下查找 json 文件,其中 lng 是语言,ns 是命名空间。

然而,我的要求是,这应该从 api 端点提供。我正在努力寻找正确的配置,因为 next-i18next 现在确实忽略了我的设置,并且没有向我的后端发出任何 xhr 请求。

next-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 - 这取决于您。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?