【问题标题】:I18next and WebpackI18next 和 Webpack
【发布时间】:2022-05-10 05:56:33
【问题描述】:

我从 Webpack 开始,发现 react i18next hook-useTranslation 有问题。

// webpack.config.js
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CopyPlugin = require("copy-webpack-plugin")

module.exports = {
    output: { 
        path: path.join(__dirname, '/dist'),
        filename: 'index.bundle.js'
    },
    devServer: {
        port: 3000,
        host: 'localhost',
        watchContentBase: true,
      
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /nodeModules/,
                use: {
                    loader: "babel-loader"
                }
            },
        ]
    },
    plugins: [
        new HtmlWebpackPlugin(
            { 
                template: './src/index.html' 
            }
        ),
        new CopyPlugin({
            patterns: [
                {
                    from: path.join(__dirname, '/public') , to: path.join(__dirname, '/dist') // copy public folder, which contains locales for i18next
                }
            ]
        })
    ],
}
//i18next.js
import i18next from 'i18next'
import { initReactI18next } from 'react-i18next'
import HttpApi from 'i18next-http-backend' 

i18next
  .use(initReactI18next)
  .use(HttpApi)
  .init(
    {
      backend: {
        loadPath: '/locales/{{lng}}/{{ns}}.json'
      },
      lng: "en_GB",
      supportedLngs: ["en_GB","cs_CZ"]
  })

export default i18next
//example.js
import React from 'react'

import { useTranslation } from 'react-i18next'

const Greeting = () => {
    const { t } = useTranslation()

    return (
        <div>
            {/* {t("common:greeting")} */}
        </div>
    )
}

export default Greeting

在浏览器中没有加载,在控制台中打印这些错误

[WDS] Disconnected!
Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: ...

我希望在公用文件夹中而不是资产中拥有语言环境,根据文档,最好将代码与翻译分开。我尝试了一切,但找不到任何解决方案。有人遇到过类似问题吗?

【问题讨论】:

  • 您的 Greeting 组件可能未在您的 React 应用程序中正确使用。你检查过日志语句中的原因吗?
  • @adrai 我不这么认为。因为当我尝试完全相同的结构但使用 create-react-app 时,它可以工作。所以问题出在 Webpack 上。

标签: reactjs webpack react-hooks i18next


【解决方案1】:

你没有定义命名空间,所以loadPath: '/locales/{{lng}}/{{ns}}.json'不会找到{{ns}}.json,因为你说你必须找到{t("common:greeting")},你要搜索的命名空间是common。所以为了修复此更改 loadPath: '/locales/{{lng}}/common.json'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-02
    • 1970-01-01
    • 2013-03-02
    • 2017-09-09
    • 1970-01-01
    • 2021-03-19
    • 2015-12-19
    • 1970-01-01
    相关资源
    最近更新 更多