I've been trying to start a new react project to practice some skills.
And recently I tried to add internationalization and localization, by adding react-i18next
and i18next
.
Simply followed the step by step guide available on https://react.i18next.com and added my translation files.
But when I run the project I get the console error GET https://localhost:8080/locales/en/generic.json 404 (Not Found)
At first I thought that the project was missing a json-loader
so I added to the webpack.config.js
, but the result is the same. I check the paths and all seems right.
Thanks in advance
i18n file
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import Backend from 'i18next-http-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
const fallbackLng = ["pt"];
const availableLanguages = ["pt", "en"];
const backendOptions = {
loadPath: "/locales/{{lng}}/{{ns}}.json",
crossDomain: true
};
i18n
// load translation using http
.use(Backend)
// detect user language
.use(LanguageDetector)
// pass the i18n instance to react-i18next.
.use(initReactI18next)
.init({
backend: backendOptions,
fallbackLng,
detection: {
checkWhitelist: true,
},
whitelist: availableLanguages,
interpolation: {
escapeValue: false // react already safes from xss
},
ns: [
"generic"
],
defaultNS: "generic",
});
export default i18n;
root file
import './i18n';
import { I18nextProvider } from 'react-i18next';
import i18n from './i18n';
const App: React.FC = React.memo(() => {
return (
<AppContainer>
<I18nextProvider i18n={i18n}>
<Router>
<React.Suspense fallback={<div>Loading...</div>}>
<MainContainer />
</React.Suspense>
</Router>
</I18nextProvider>
</AppContainer>
)
});
ReactDOM.render(<App />, document.getElementById('root'))
Extras
tsconfig.json
{
"compilerOptions": {
"outDir": "./dist",
"module": "esnext",
// Target latest version of ECMAScript.
"target": "esnext",
// Search under node_modules for non-relative imports.
"moduleResolution": "node",
// Process & infer types from .js files.
"allowJs": true,
// Don't emit; allow Babel to transform files.
"noEmit": true,
// Enable strictest settings like strictNullChecks & noImplicitAny.
"strict": true,
// Disallow features that require cross-file information for emit.
"isolatedModules": false,
// Import non-ES modules as default imports.
"esModuleInterop": true,
"checkJs": false,
"skipLibCheck": false,
"noImplicitAny": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"jsx": "react",
"lib": [
"ES6",
"dom",
"dom.iterable",
],
},
"baseUrl": "./",
"paths": {
"@assets/*": [
"src/assets/*"
]
},
"include": [
"src",
"./externals.d.ts",
],
"exclude": [
"node_modules",
"webpack.*.js"
]
}
So I think that o discovered a solution
All I did was add the copy-webpack-plugin
and put the following code to my webpack file
const common = {
...
plugins: [
...
new CopyPlugin([
{ from: "./src/locales", to: "locales" },
]),
]
}