我正在初始化 i18next
但得到的是错误信息。
Uncaught TypeError: Cannot read property 'use' of undefined
以下是我的代码。
import i18n from 'i18next';// Getting eslint error Module imports itself.
import { initReactI18next } from 'react-i18next';
import Backend from 'i18next-xhr-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
const fallbackLng = ['en'];
const availableLanguages = ['en', 'ar', 'fr'];
i18n
.use(Backend)
.use(LanguageDetector)
.use(initReactI18next)
.init({
fallbackLng,
detection: {
checkWhitelist: true,
},
debug: false,
whitelist: availableLanguages,
interpolation: {
escapeValue: false,
},
});
export default i18n;
反应: 16.13.1
i18next: 19.4.5
在index.js中的App节点被挂载的地方,你是否有 import './i18n'
也有吗?对于我的设置,除了你展示的文件外,还需要这个文件。
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import {unregister} from './serviceWorker.js'
import './i18n';
ReactDOM.render(<App />, document.getElementById('root'));
unregister()
我有一个i18n.js文件,这是我自己的配置,用于加载和初始化我的设置。
// i18n.js
// https://codesandbox.io/s/react-i18next-basic-example-with-usetranslation-hook-l05ml
import i18n from "i18next";
import Backend from "i18next-xhr-backend";
import LanguageDetector from "i18next-browser-languagedetector";
import { initReactI18next } from "react-i18next";
import moment from 'moment/moment'
import 'moment/min/locales';
i18n
// load translation using xhr -> see /public/locales
// learn more: https://github.com/i18next/i18next-xhr-backend
.use(Backend)
// detect user language
// learn more: https://github.com/i18next/i18next-browser-languageDetector
.use(LanguageDetector)
// pass the i18n instance to react-i18next.
.use(initReactI18next)
// for all options read: https://www.i18next.com/overview/configuration-options
.init({
fallbackLng: "en-GB",
detection: {
// https://github.com/i18next/i18next-browser-languageDetector
order: ['navigator'],
},
debug: false,
interpolation: {
escapeValue: false, // not needed for react as it escapes by default
format: function (value, format, lng) {
if (format === 'uppercase') return value.toUpperCase();
if (value instanceof Date) {
var result = moment(value).locale(lng).format(format);
return result;
}
if (format === 'intlDate') {
return new Intl.DateTimeFormat(lng).format(value);
}
return value;
},
defaultVariables : {
product: "Word Pigeon"
}
},
// keySeparator: '_',
react: {
wait: true,
escapeValue: false // not needed for react as it escapes by default
}
});