[英]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.