嗨,我试图在我的应用程序中支持多语言,但我必须通过从 express 获得的响应来访问密钥。我在 react 和 express 中使用 i18n 从后端获取翻译。就像这对我有用:
t('en.translation.user')
但我想这样做:
t('user')
这是我在客户端的代码:
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import Backend from "i18next-http-backend";
i18n
.use(Backend)
.use(initReactI18next)
.init({
lng: "en",
fallbackLng: "en",
backend: {
loadPath: "http://localhost:4000/locales/resources.json?lng={{lng}}&ns={{ns}}",
addPath: "http://localhost:4000/locales/add/{{lng}}/{{ns}}",
allowMultiLoading: false,
},
interpolation: {
escapeValue: false, // react already safes from xss
},
});
export default i18n;
我的服务器是这样的:
const i18next = require('i18next');
const Backend = require('i18next-node-fs-backend');
const i18nextMiddleware = require('i18next-express-middleware');
const pathTranslationPublic = path.join(__dirname, '/src/locales');
i18next.use(Backend).init({
preload: ['en',],
lowerCaseLng: true,
backend: {
loadPath: `${pathTranslationPublic}/{{lng}}/{{ns}}.json`,
addPath: `${pathTranslationPublic}/{{lng}}/{{ns}}.missing.json`,
jsonIndent: 4,
},
load: 'all',
lng: 'en',
fallbackLng: 'en',
debug: true,
saveMissing: true,
formatSeparator:'.'
});
app.use(
i18nextMiddleware.handle(i18next, {
removeLngFromUrl: false,
}),
);
app.get(
'/locales/resources.json',
i18nextMiddleware.getResourcesHandler(i18next),
);
这是来自客户的回应:
{
"en": {
"translation": {
"user": "hello user"
}
}
}