【发布时间】: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