Getting i18next undefined - javascript

I am initializing i18next but getting error:
Uncaught TypeError: Cannot read property 'use' of undefined
Following is my code:
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;
react: 16.13.1
i18next: 19.4.5

In the index.js where the App node is mounted did you import './i18n' there also? For my setup this was required in addition to the file you showed.
// 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()
I have a i18n.js file which is my own config for loading and initialising with my settings
// 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
}
});

You could try using import * as i18n from 'i18next' and then mock out i18n mocks if you need. For example:
const i18nMock = {}
i18nMock.use = jest.fn().mockReturnValue(i18nMock)
i18nMock.init = jest.fn()
module.exports = i18nMock

Related

Vue.js how to get current locale in i18n language package

i want to get my current locale , because i need to check if the current locale === 'en' then return true or false, how can i do this? Vue.js/i18n/vee-validate
main.js :
import { createApp } from "vue";
import { createPinia } from "pinia";
import "./index.css";
import App from "./App.vue";
import router from "./router";
import "#/config/vee-validate/rules";
import "#/config/vee-validate/messages";
const app = createApp(App);
app.use(createPinia());
app.use(router);
app.mount("#app");
In option API use :
this.$i18n.locale
in composition API use the useI18n function to get the locale :
const {locale}=useI18n()

How to use i18n in the Vuex store

I have a project where I need to do translations inside the Vuex store. But I keep on getting an error when trying to translate using i18n inside the store.
I have tried to import and instance of i18n inside the store using the following import statement. But I then I get an error Uncaught TypeError: _i18n__WEBPACK_IMPORTED_MODULE_3__.default.t is not a function
import i18n from '#/i18n';
In the main.js file of my Vue project I import and use the i18n file:
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import { store } from './store';
import i18n from './i18n';
createApp(App).use(i18n).use(store).use(router).mount('#app');
This is my i18n.js file that is located inside the src folder:
import { createI18n } from 'vue-i18n';
function loadLocaleMessages() {
const locales = require.context(
'./locales',
true,
/[A-Za-z0-9-_,\s]+\.json$/i
);
const messages = {};
locales.keys().forEach((key) => {
const matched = key.match(/([A-Za-z0-9-_]+)\./i);
if (matched && matched.length > 1) {
const locale = matched[1];
messages[locale] = locales(key);
}
});
return messages;
}
export default createI18n({
legacy: false,
locale: localStorage.locale ?? 'nl',
globalInjection: true,
messages: loadLocaleMessages(),
});
For Vue 3 guys out there struggling with usage of i18n in the Vuex store, I was able to achieve it like this:
translations/index.js
with basic setup
import { createI18n } from 'vue-i18n'
const i18n = createI18n({
fallbackLocale: 'en',
globalInjection: true,
messages: messages
})
export default i18n
main.js
Import store and i18n and use them in Vue app instance
import i18n from './translations'
import store from './store'
const app = createApp(App)
app.use(store)
app.use(i18n)
app.mount('#app')
Vuex store module file with getter example:
import i18n from './translations'
const getters = {
getNotification: (state) => {
...
notification.title = i18n.global.t('notification.title')
...
}
}
I used vue-i18n in Vuex. Maybe it helps to you.
Create vue-i18n.js file like this;
import Vue from "vue";
import VueI18n from "vue-i18n";
// Localisation language list
import { locale as en } from "#/core/config/i18n/en.js";
import { locale as ch } from "#/core/config/i18n/ch.js";
Vue.use(VueI18n);
let messages = {};
messages = { ...messages, en, ch };
// get current selected language
const lang = localStorage.getItem("language") || "en";
// Create VueI18n instance with options
const i18n = new VueI18n({
locale: lang, // set locale
messages // set locale messages
});
export default i18n;
and import it to Vue in main.js file;
import i18n from "#/core/plugins/vue-i18n";
new Vue({
router,
store,
i18n,
render: h => h(App),
}).$mount('#app')
import it inside your store or modules ( i imported in my vuex module);
import i18n from "#/core/plugins/vue-i18n";
then use it wherever you want (action, mutation, setter or getter);
const sample = i18n.t('ERRORS.NETWORKERROR');
en.js file;
export const locale = {
LOGIN: {
OPERATORID: "Operator ID",
SIGNIN:"Sign In",
SCANCARD: "Scan Card"
},
ERRORS: {
NETWORKERROR: "Network error occurred!",
UNAUTHUSERERROR: "Unauthorized user!",
}
};

How to get i18next.t() in plain JS file?

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
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'
});

Change I18n locale don't work for Vee-Validate - VueJS

I am using Vee-Validate plugin for form validation in my VueJS Application. So, my app has more than 1 language, for that, I am using I18n. All the plugins I am using are in separate files under plugins folder and then I am getting all files and registering all plugins in main.js, so in my Vee-Validate.js I have written:
import Vue from 'vue';
import VueI18n from 'vue-i18n';
import VeeValidate from 'vee-validate';
import enMessages from "./../locales/validation/en";
import urMessages from "./../locales/validation/ur";
Vue.use(VueI18n);
const i18n = new VueI18n();
i18n.locale = "en";
Vue.use(VeeValidate, {
errorBagName: 'vErrors',
i18nRootKey: 'validations',
i18n,
dictionary: {
en: {
messages: enMessages
},
ur: {
messages: urMessages
}
}
});
But on clicking the change locale button don't change this file locale,
My change locale function:
changeLocale () {
this.$i18n.locale == 'en' ? this.$i18n.locale = 'ur' : this.$i18n.locale = 'en'
this.$vuetify.rtl = this.$i18n.locale == 'ur' ? true : false;
}
Well, I'm not saying your configuration is wrong. I'm going just share mine that is working just fine.
1- vue.config.js
module.exports = {
transpileDependencies: [
'vuetify',
],
pluginOptions: {
i18n: {
locale: 'en',
fallbackLocale: 'en',
localeDir: 'locales',
enableInSFC: true,
},
},
};
2- i18n.ts
import Vue from 'vue';
import VueI18n, { LocaleMessages } from 'vue-i18n';
Vue.use(VueI18n);
function loadLocaleMessages(): LocaleMessages {
const locales = require.context('./locales', true, /[A-Za-z0-9-_,\s]+\.json$/i);
const messages: LocaleMessages = {};
locales.keys().forEach((key) => {
const matched = key.match(/([A-Za-z0-9-_]+)\./i);
if (matched && matched.length > 1) {
const locale = matched[1];
messages[locale] = locales(key);
}
});
return messages;
}
export default new VueI18n({
locale: process.env.VUE_APP_I18N_LOCALE || 'en',
fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'en',
messages: loadLocaleMessages(),
});
3- main.ts
import Vue from 'vue';
import './registerServiceWorker';
import { sync } from 'vuex-router-sync';
import VueLodash from 'vue-lodash';
import Storage from 'vue-ls';
import vuetify from './plugins/vuetify';
import './utils/vee-validate';
// Components
import './components';
// Application imports
import App from './App.vue';
import router from '#/router';
import store from '#/store';
import i18n from './i18n';
// Sync store with router
sync(store, router);
const options = {
name: 'ls', // name variable Vue.[ls] or this.[$ls],
storage: 'local', // storage name session, local, memory
};
Vue.use(Storage, options);
Vue.config.productionTip = false;
Vue.use(VueLodash, { name: 'lodash' });
new Vue({
router,
store,
vuetify,
i18n,
render: h => h(App),
}).$mount('#app');
4- src/plugins/vuetify.ts
import Vue from 'vue';
import Vuetify from 'vuetify/lib';
// import VueI18n from 'vue-i18n';
// import i18n from '#/i18n';
import en from '#/locales/en.json';
import jp from '#/locales/jp.json';
Vue.use(Vuetify);
export default new Vuetify({
lang: {
locales: { en, jp },
current: 'jp',
},
});
5- src/utils/vee-validate.js
/* eslint-disable no-underscore-dangle */
import { extend } from 'vee-validate';
import { required, email, confirmed } from 'vee-validate/dist/rules';
import i18n from '#/i18n';
extend('required', {
...required,
message: (_, values) => i18n.t('GENERAL_VALIDATION_MESSAGES_REQUIRED', values),
});
extend('email', {
...email,
message: (_, values) => i18n.t('LOGIN_FORM_EMAIL_VALID_MESSAGE', values),
});
extend('confirmed', {
...confirmed,
message: (_, values) => i18n.t('CHANGE_PASSWORD_FORM_CONFIRMATION_VALID_MESSAGE', values),
});
6- I use vuex so from my language store
import Vue from 'vue';
import { localize } from 'vee-validate';
import Vuetify from 'vuetify/lib';
import i18n from '#/i18n';
import en from '#/locales/en.json';
import jp from '#/locales/jp.json';
...
const mutations = {
SET_LANG(state, data) {
state.lang = data;
i18n.locale = data;
localize(data, jp);
},
SET_LANG_ERROR() {
window.$messageGlobal('Error switching languages');
},
};
Hope it helps

Vue CLI and Server-Side Rendering

I'm using Vue CLI which uses main.js to mount the app versus Server-Side Rendering (according to the tutorial I follow here) which uses app.js, entry-client.js and entry-server.js.
I tried to bypass main.js, but I'm having an error since its seems its required some how.
How can I work to keep main.js with app.js, entry-client.js and entry-server.js.
It might be a very basic question and I could maybe use the content of app.js in main.js, be I want to do things right.
main.js :
import Vue from 'vue'
import bootstrap from 'bootstrap'
import App from './App.vue'
import router from './router'
import store from './store'
import VueResource from 'vue-resource'
import BootstrapVue from 'bootstrap-vue'
import './registerServiceWorker'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
Vue.config.productionTip = false
Vue.use(VueResource)
Vue.use(BootstrapVue)
new Vue({
bootstrap,
router,
store,
render: h => h(App)
}).$mount('#app')
app.js :
import Vue from 'vue'
import App from './App.vue'
import bootstrap from 'bootstrap'
import { createRouter } from './router'
import store from './store'
import VueResource from 'vue-resource'
import BootstrapVue from 'bootstrap-vue'
import './registerServiceWorker'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
Vue.config.productionTip = false
Vue.use(VueResource)
Vue.use(BootstrapVue)
export function createApp () {
// create router instance
const router = createRouter()
const app = new Vue({
bootstrap,
router,
store,
render: h => h(App)
})
return { app, bootstrap, router, store }
}
server-client.js
import { createApp } from './app'
const { app, router } = createApp()
router.onReady(() => {
app.$mount('#app')
})
entry-server.js
import { createApp } from './app'
export default context => {
// since there could potentially be asynchronous route hooks or components,
// we will be returning a Promise so that the server can wait until
// everything is ready before rendering.
return new Promise((resolve, reject) => {
const { app, router } = createApp()
// set server-side router's location
router.push(context.url)
// wait until router has resolved possible async components and hooks
router.onReady(() => {
const matchedComponents = router.getMatchedComponents()
// no matched routes, reject with 404
if (!matchedComponents.length) {
return reject({ code: 404 })
}
// the Promise should resolve to the app instance so it can be rendered
resolve(app)
}, reject)
})
}
Any help is greatly appreciated.
I just found how. By default, Vue CLI 3 comes with no vue.config.js. I had to create one at the root of the folder to override the entry which was set to /src/main.js.
I used the vue.config.js found on this github and onverwrittes the entry to ./src/entry-${target}
const VueSSRServerPlugin = require('vue-server-renderer/server-plugin')
const VueSSRClientPlugin = require('vue-server-renderer/client-plugin')
const nodeExternals = require('webpack-node-externals')
const merge = require('lodash.merge')
const TARGET_NODE = process.env.WEBPACK_TARGET === 'node'
const createApiFile = TARGET_NODE
? './create-api-server.js'
: './create-api-client.js'
const target = TARGET_NODE
? 'server'
: 'client'
module.exports = {
configureWebpack: () => ({
entry: `./src/entry-${target}`,
target: TARGET_NODE ? 'node' : 'web',
node: TARGET_NODE ? undefined : false,
plugins: [
TARGET_NODE
? new VueSSRServerPlugin()
: new VueSSRClientPlugin()
],
externals: TARGET_NODE ? nodeExternals({
whitelist: /\.css$/
}) : undefined,
output: {
libraryTarget: TARGET_NODE
? 'commonjs2'
: undefined
},
optimization: {
splitChunks: undefined
},
resolve:{
alias: {
'create-api': createApiFile
}
}
}),
chainWebpack: config => {
config.module
.rule('vue')
.use('vue-loader')
.tap(options =>
merge(options, {
optimizeSSR: false
})
)
}
}

Categories

Resources