最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get i18next.t() in plain JS file? - Stack Overflow

programmeradmin1浏览0评论

Overview

React application in which internationalization is required, using i18next to achieve this.

Problem

In project structure there is constants.js (Plain JS) where I am trying to get i18next.t() for translation. Please find the relevant code.

index.js

import React,{Suspense} from "react";
import ReactDOM from "react-dom";
import "./style/index.scss";
import App from "./app";
import createSagaMiddleware from "redux-saga";
import { createStore, applyMiddleware } from "redux";
import { Provider } from "react-redux";
import rootReducer from "./reducers";
import rootSaga from "./sagas";
import './i18n';

const sagaMiddleware = createSagaMiddleware();
const store = createStore(rootReducer, applyMiddleware(sagaMiddleware));
sagaMiddleware.run(rootSaga);

ReactDOM.render(<Provider store={store}>

    <App store={store} />

</Provider>,
    document.getElementById("root")
);

App.js

import React from "react";
import "./App.scss";
import MyOrders from "../component/my-orders";
import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import i18n from 'i18next'

toast.configure({ autoClose: 5000 });

const changeLanguage = (lng) => {
    i18n.changeLanguage(lng);
};


const App = () => {


    return (
        <div className="App">
            <div align="left">
                <button className="btn btn-group-sm" onClick={() => changeLanguage('de')}>German</button>
                <button className="btn btn-group-sm" onClick={() => changeLanguage('en')}>English</button>
            </div>
            <MyOrders />
        </div>
    );
};

export default App;

i18n.js

import i18n from "i18next";
import detector from "i18next-browser-languagedetector";
import { reactI18nextModule } from "react-i18next";

import translationEN from '../public/locales/en/translation.json';
import translationDE from '../public/locales/de/translation.json';

// the translations
const resources = {
  en: {
    translation: translationEN
  },
  de: {
    translation: translationDE
  }
};

i18n
  .use(detector)
  .use(reactI18nextModule) // passes i18n down to react-i18next
  .init({
    resources,
    lng: "en",
    fallbackLng: "en", // use en if detected lng is not available

    interpolation: {
      escapeValue: false // react already safes from xss
    }
  });

export default i18n;

Question Updates with progress so far

constants.js (Plain JavaScript file, exporting multiple constant objects)

import i18n from "../../i18n";
import { withNamespaces } from "react-i18next";

function parentFunction(){
   let constantsMap = new Map();
   constantsMap.set("constant1", valueOfConstant1);
   ....
}
export default withNamespaces()(parentFunction)

translation.js (de)

{
"MODAL": {
    "CANCEL": "Stornieren",
    "UPDATE": "Aktualisieren",
    "SAVE": "Speichern",
    "CANCEL_BOD": "Ja, Abbrechen BOD",
    "KEEP_BOD": "Nein, behalte BOD",
    "NEXT": "Nächster"
}, .....

I tried the following solution with no luck: Solution

Overview

React application in which internationalization is required, using i18next to achieve this.

Problem

In project structure there is constants.js (Plain JS) where I am trying to get i18next.t() for translation. Please find the relevant code.

index.js

import React,{Suspense} from "react";
import ReactDOM from "react-dom";
import "./style/index.scss";
import App from "./app";
import createSagaMiddleware from "redux-saga";
import { createStore, applyMiddleware } from "redux";
import { Provider } from "react-redux";
import rootReducer from "./reducers";
import rootSaga from "./sagas";
import './i18n';

const sagaMiddleware = createSagaMiddleware();
const store = createStore(rootReducer, applyMiddleware(sagaMiddleware));
sagaMiddleware.run(rootSaga);

ReactDOM.render(<Provider store={store}>

    <App store={store} />

</Provider>,
    document.getElementById("root")
);

App.js

import React from "react";
import "./App.scss";
import MyOrders from "../component/my-orders";
import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import i18n from 'i18next'

toast.configure({ autoClose: 5000 });

const changeLanguage = (lng) => {
    i18n.changeLanguage(lng);
};


const App = () => {


    return (
        <div className="App">
            <div align="left">
                <button className="btn btn-group-sm" onClick={() => changeLanguage('de')}>German</button>
                <button className="btn btn-group-sm" onClick={() => changeLanguage('en')}>English</button>
            </div>
            <MyOrders />
        </div>
    );
};

export default App;

i18n.js

import i18n from "i18next";
import detector from "i18next-browser-languagedetector";
import { reactI18nextModule } from "react-i18next";

import translationEN from '../public/locales/en/translation.json';
import translationDE from '../public/locales/de/translation.json';

// the translations
const resources = {
  en: {
    translation: translationEN
  },
  de: {
    translation: translationDE
  }
};

i18n
  .use(detector)
  .use(reactI18nextModule) // passes i18n down to react-i18next
  .init({
    resources,
    lng: "en",
    fallbackLng: "en", // use en if detected lng is not available

    interpolation: {
      escapeValue: false // react already safes from xss
    }
  });

export default i18n;

Question Updates with progress so far

constants.js (Plain JavaScript file, exporting multiple constant objects)

import i18n from "../../i18n";
import { withNamespaces } from "react-i18next";

function parentFunction(){
   let constantsMap = new Map();
   constantsMap.set("constant1", valueOfConstant1);
   ....
}
export default withNamespaces()(parentFunction)

translation.js (de)

{
"MODAL": {
    "CANCEL": "Stornieren",
    "UPDATE": "Aktualisieren",
    "SAVE": "Speichern",
    "CANCEL_BOD": "Ja, Abbrechen BOD",
    "KEEP_BOD": "Nein, behalte BOD",
    "NEXT": "Nächster"
}, .....

I tried the following solution with no luck: Solution

Share Improve this question edited Feb 12, 2020 at 7:11 Zain Ul Abideen asked Feb 11, 2020 at 7:57 Zain Ul AbideenZain Ul Abideen 1,6021 gold badge12 silver badges26 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 13

You can import i18n instance from your i18n.js file, it contains t on it.

import i18n from '../i18n';

i18n.t // <- use it.

I used it this way on redux saga

import i18n from "i18next";
      toast.error(i18n.t('thereWasAnErrorUpdating'), {
            position: toast.POSITION.TOP_CENTER,
            autoClose: NOTIFICATION_TIME,
            toastId: 'settingInformationFailure'
        });
发布评论

评论列表(0)

  1. 暂无评论