React Native i18next Backend not loading json files - react-native

Hi I am using i18next with React Native for translations, but am getting the following error when trying to load json files:
i18next::backendConnector: lloading namespace translation for language en failed failed loading ./locales/en/translation.json
and also
i18next::translator: missingKey en translation screens.login.header screens.login.header
app/i18n.js
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import Fetch from 'i18next-fetch-backend';
const languageDetector = {
type: 'languageDetector',
async: true,
detect: cb => cb('en'),
init: () => {},
cacheUserLanguage: () => {},
};
i18n
.use(Fetch)
.use(languageDetector)
.use(initReactI18next)
.init({
lng: 'en',
debug: true,
interpolation: {
escapeValue: false,
formatSeparator: ',',
},
keySeparator: '.',
whitelist: ['en'],
nonExplicitWhitelist: true,
fallbackLng: 'en',
backend: {
loadPath: './locales/{{lng}}/{{ns}}.json',
allowMultiLoading: true,
},
react: {
wait: true,
},
});
export default i18n;
app/locales/en/translation.json
{
"screens": {
"login": {
"header": "Login to your your account",
"loginButton": "Login"
}
}
}
app/screens/auth/LoginScreen.js
{t('screens.login.header')}
Has anyone had any success using this library with React Native?

Related

Vite: vue-i18n build fail

Everything work fine in dev mode, but when try to npm run build, Unexpected token error in vue-i18n
import { createI18n } from 'vue-i18n';
import messages from '#intlify/vite-plugin-vue-i18n/messages'
const i18n = createI18n({
locale: 'en',
legacy: false,
fallbackLocale: 'en',
globalInjection: true,
messages
})
export default i18n;
//vite.config.js
import { defineConfig } from 'vite'
import vue from '#vitejs/plugin-vue'
import path from 'path'
import vueI18n from '#intlify/vite-plugin-vue-i18n'
export default defineConfig({
plugins: [
vue(),
vueI18n({
// if you want to use Vue I18n Legacy API, you need to set `compositionOnly: false`
// compositionOnly: false,
// you need to set i18n resource including paths !
include: path.resolve(__dirname, './src/locales/**'),
}),
],
resolve: {
alias: {
'#': path.resolve(__dirname, './src'),
},
},
})
Error:
[commonjs--resolver] Unexpected token (249:14) in E:/Work/Vue/vue-sample/node_modules/vue-i18n/dist/vue-i18n.runtime.esm-bundler.js
247: if (locales.length) {
248: locales.forEach(locale => {
249: global.mergeLocaleMessage(locale, messages[locale]);
^
250: });
251: }

How use vue-i18n with vue2, vite?

i'm migrating from webpack to vite, but there is a problem that I can't find a plugin to use i18n
I tried to use #intlify/vite-plugin-vue-i18n: 6.0.1, it doesn't seem to be work
now my package version:
vue: 2.6.11
vue-i18n: 8.17.0
#kazupon/vue-i18n-loader: 0.5.0
#intlify/vite-plugin-vue-i18n: 6.0.1
vite: 2.9.15
vite-plugin-vue2: 2.0.2
vite.config.js
/* cSpell:disable */
import { defineConfig } from 'vite';
const { resolve } = require('path');
import { createVuePlugin } from 'vite-plugin-vue2';
import copy from 'rollup-plugin-copy';
import { viteCommonjs } from '#originjs/vite-plugin-commonjs';
import clear from 'rollup-plugin-clear';
import vueI18n from '#intlify/vite-plugin-vue-i18n';
import { createI18nPlugin } from '#yfwz100/vite-plugin-vue2-i18n';
const destDir = `../var/dist/views`;
const host = 'localhost';
let filePort;
try {
const port = require('../port');
filePort = port && port.front;
// eslint-disable-next-line no-empty
} catch (error) {}
const listenPort = filePort || '10210';
const pages = {
cn: {
dir: 'pages',
template: 'cn.html',
entry: 'cn.js'
},
'vue-test': {
dir: 'vue-test/index',
template: 'index.html',
entry: 'index.js'
}
};
const multiplePagePath = 'src/pages';
const copyFileList = [];
Object.values(pages).forEach(item => {
copyFileList.push({
src: `${multiplePagePath}/${item.dir}/${item.template}`,
dest: destDir + '/' + item.dir,
transform: (contents, filename) =>
contents
.toString()
.replace(
'<!-- viteDevelopmentCopyReplaceHref -->',
`<script src="//${host}:${listenPort}/${multiplePagePath}/${item.dir}/${item.entry}" type="module" ></script>`
)
});
});
export default defineConfig({
resolve: {
alias: { src: resolve(__dirname, './src') },
extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
},
server: {
port: listenPort,
// https: true,
hmr: { host },
origin: `//${host}:${listenPort}`
},
plugins: [
createVuePlugin(),
clear({
targets: ['../var']
}),
copy({
targets: [...copyFileList, { src: 'src/pages/*.html', dest: destDir }, { src: 'src/pages/layout', dest: destDir }],
verbose: true,
hook: 'buildStart'
}),
vueI18n({
// if you want to use Vue I18n Legacy API, you need to set `compositionOnly: false`
// compositionOnly: false,
// you need to set i18n resource including paths !
// include: resolve(__dirname, './path/to/src/locales/**'),
compositionOnly: false
})
]
});
index.vue
<i18n>
{
"en-us": {
"language": "Language",
"hello": "hello, world!"
},
"zh-cn": {
"language": "言語",
"hello": "こんにちは、世界!"
}
}
</i18n>
<template>
<div id="app">
<p>{{$t('language')}}</p>
</div>
</template>
<script>
</script>
when i open the page, the text has not been translated and there is a warning in console:
[vue-i18n] Cannot translate the value of keypath 'language'. Use the value of keypath as default
Can anyone help me on this? Thanks in Advance
#intlify/vite-plugin-vue-i18n does not support custom block in Vue 2.
You should use unplugin-vue-i18n with vue-i18n-bridge.
Minimal examples of Vue2 + VueI18n custom block + Vite:
Vue<=2.6: https://stackblitz.com/edit/vitejs-vite-wk6hhj
Vue 2.7: https://stackblitz.com/edit/vitejs-vite-elfdtq
I18n Legacy API:
Vue<=2.6: https://stackblitz.com/edit/vitejs-vite-ed3cmt

i18next react load namespaces only when needed

I have the following code that loads i18n translations. The l.json file exists only in a few pages but it is loaded always (based on the http requests that I see from the browser). How can I prevent it so that these are loaded only when needed?
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import ChainedBackend from 'i18next-chained-backend';
import HttpBackend from 'i18next-http-backend';
i18n
.use(LanguageDetector)
.use(initReactI18next)
.use(ChainedBackend)
.init({
debug: true,
fallbackLng: "en-US",
supportedLngs: ['en-US', 'en-GB'],
ns: ['l', 't'],
defaultNS: 't',
interpolation: {
escapeValue: false, // not needed for react as it escapes by default
},
backend: {
backends: [
HttpBackend,
],
backendOptions: [
{
loadPath: 'https://example.com/{{lng}}/{{ns}}.json'
}
]
}
});

How to test react-native components which are using react-i18next?

I'm trying to use jest to start testing an established RN app. The majority of the components are wrapped in withNamespaces provided by react-i18next.
When i run tests i have this error:
FAIL tests/setting.test.js
● Test suite failed to run
TypeError: Cannot read property 'type' of undefined
4 |
5 | i18n
> 6 | .use(initReactI18next)
| ^
7 | .init({
8 | fallbackLng: 'en',
9 | resources: {
at I18n.use (node_modules/i18next/dist/commonjs/i18next.js:260:16)
at Object.<anonymous> (config/i18nForTest.js:6:1)
at Object.<anonymous> (tests/setting.test.js:5:43)
I followed the doc example and what i've done basically is :
made i18n config for tests :
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
i18n
.use(initReactI18next)
.init({
fallbackLng: 'en',
resources: {
en: {},
fr: {}
},
// have a common namespace used around the full app
ns: ['translations'],
defaultNS: 'translations',
debug: true,
interpolation: {
escapeValue: false, // not needed for react!!
},
});
export default i18n;
then wrote some tests:
import 'react-native';
import React from 'react';
import renderer from 'react-test-renderer';
import {I18nextProvider} from 'react-i18next';
import i18n from 'config/i18nForTest';
import Settings from 'containers/Settings';
it('Does Settings renders correctly?', () => {
const tree = renderer
.create(
<I18nextProvider i18n={i18n}>
<Settings t= {key => key} />
</I18nextProvider>,
)
.toJSON();
expect(tree).toMatchSnapshot();
});
you can find here my jest config in package.json:
"jest": {
"setupFiles": ["<rootDir>/jest.setup.js"],
"preset": "react-native",
"testMatch": [
"<rootDir>/tests/**/*.test.js?(x)",
"<rootDir>/src/**/*.test.js"
],
"transformIgnorePatterns": ["node_modules/(?!(#react-native-community|react-navigation|react-native))"
],
"transform": {
"^.+\\.(js)$": "<rootDir>/node_modules/react-native/jest/preprocessor.js"
}
},
THANKS!
I finally found a solution for my problem.
I think the testing example provided in the doc is for v10 and i'm using v9.
So i have modified the i18n config test to use reactI18nextModule so its like this now:
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import { reactI18nextModule } from 'react-i18next';
i18n
.use(reactI18nextModule)
.init({
fallbackLng: 'en',
resources: {
en: {},
fr: {}
},
// have a common namespace used around the full app
ns: ['translations'],
defaultNS: 'translations',
debug: true,
interpolation: {
escapeValue: false, // not needed for react!!
},
});
export default i18n;
after that now i can omit i18nProvider in the testing components like this:
import 'react-native';
import React from 'react';
import renderer from 'react-test-renderer';
import {I18nextProvider} from 'react-i18next';
import i18n from 'config/i18nForTest';
import {Settings} from 'containers/Settings'; // to get redux connected component import Setting without {}
it('Does Settings renders correctly?', () => {
const tree = renderer
.create(
<Settings t={key => key} />
)
.toJSON();
expect(tree).toMatchSnapshot();
});

integrate i18next with redux

I am trying to detect the locale from one of this 2 options:
1. if user selected one - application opened at least once
2. if app opens for the very 1st time - use device locale.
I tried using this guide and this bit of code i18next-react-native-language-detector. but with no help.
my i18n.js file looks like:
import i18next from 'i18next';
import { AsyncStorage } from 'react-native';
(*) // import i18nextReactNative from 'i18next-react-native-language-detector';
import locale from 'react-native-locale-detector';
import en from './en';
import de from './de';
const languageDetector = {
init: Function.prototype,
type: 'languageDetector',
async: true, // flags below detection to be async
detect: () => AsyncStorage.getItem('APP:lnag')
.then((savedDataJSON) => {
const savedLocal = JSON.parse(savedDataJSON);
const selectLanguage = savedLocal || locale;
return selectLanguage;
}),
cacheUserLanguage: Function.prototype,
};
let translate;
i18next
(*)//.use(i18nextReactNative)
(**).use(languageDetector)
.init({
fallbackLng: 'en',
resources: {
en,
de,
},
react: {
wait: true,
},
// have a common namespace used around the full app
ns: ['common'],
defaultNS: 'common',
debug: true,
interpolation: {
escapeValue: false, // not needed for react!!
formatSeparator: ',',
format(value, format) {
if (format === 'uppercase') return value.toUpperCase();
return value;
},
},
}, (err, t) => {
translate = t;
});
export { translate as t };
export default i18next;
But I getting an error: TypeError: (0, _18n.t) is not a function.
When I use default languageDetector, remove comment from lines (*) and comment the custom languageDetector it works fine but not as I want - always takes device locale
I found a solution:
import i18next from 'i18next';
import { AsyncStorage } from 'react-native';
import locale from 'react-native-locale-detector';
import en from './en';
import de from './de';
const languageDetector = {
init: Function.prototype,
type: 'languageDetector',
async: true, // flags below detection to be async
detect: async (callback) => {
const savedDataJSON = await AsyncStorage.getItem(STORAGE_KEY);
const lng = (savedDataJSON) ? JSON.parse(savedDataJSON): null;
const selectLanguage = lng || locale;
console.log('detect - selectLanguage:', selectLanguage);
callback(selectLanguage);
},
cacheUserLanguage: () => {}
}
let translate;
i18next
.use(languageDetector)
.init({
fallbackLng: 'en',
resources: { en, de},
react: { wait: false },
// have a common namespace used around the full app
ns: ['common'],
defaultNS: 'common',
debug: true,
interpolation: {
escapeValue: false, // not needed for react!!
formatSeparator: ',',
format(value, format) {
if (format === 'uppercase') return value.toUpperCase();
return value;
},
},
}, (err, t) => {
translate = t;
});
export { translate as t };
export default i18next;