首页 > 解决方案 > I18next 和 Webpack

问题描述

我从 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: ...

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

标签: reactjswebpackreact-hooksi18next

解决方案


推荐阅读