![](/img/trans.png)
[英]Testing i18next complain about "Cannot read property 'use' of undefined"
[英]TypeError - Cannot read property 'use' of undefined when using i18next
我有一个具有以下依赖项的项目:
"dependencies": {
"@hapi/joi": "^17.1.1",
"bcrypt": "^5.0.1",
"config": "^3.3.7",
"express": "^4.17.3",
"express-async-errors": "^3.1.1",
"express-rest-i18n": "^1.0.1",
"http-status-codes": "^2.2.0",
"i18next": "^21.6.14",
"i18next-http-backend": "^1.4.0",
"i18next-http-middleware": "^3.2.0",
"joi": "^17.4.2",
"lodash": "^4.17.21",
"mongoose": "^6.2.4",
"validator": "^13.7.0"
},
我的 i18n 配置代码如下:
const i18next = require("i18next").default;
const Backend = require("i18next-http-backend").default;
const i18nextMiddleware = require("i18next-http-middleware");
i18next
.use(Backend)
.use(i18nextMiddleware.LanguageDetector)
.init({
backend: {
loadPath: __dirname + `/locales/{{lng}}/{{ns}}.json`,
},
fallbackLng: "en",
preload: ["en"],
});
module.exports = { i18next };
我的应用程序代码如下:
const { i18next } = require("../locales/i18n");
const messages = require("../locales/en/translation.json");
const i18nextMiddleware = require("i18next-http-middleware");
require("express-async-errors");
const express = require("express");
const app = express();
app.use(express.json());
app.use(i18nextMiddleware.handle(i18next));
app.get("*", (req, res) => {
const response = req.t("greeting");
res.status(200);
res.send(response);
});
const port = process.env.PORT || 3000;
module.exports = app.listen(port, () =>
console.log(`Listening on port: ${port}`)
);
当我通过运行 npm start 启动应用程序时,我收到错误: TypeError: Cannot read property 'use' of undefined
存在此错误是因为配置文件中的 Backend 未定义。 我使用https://www.npmjs.com/package/i18next-http-middleware作为资源。
为什么我会收到此错误,我该如何解决?
你为什么访问.default?
像这样导入:
const i18next = require("i18next");
const Backend = require("i18next-http-backend");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.