【发布时间】:2021-04-11 01:58:22
【问题描述】:
我一直在尝试开始一个新的 React 项目来练习一些技能。
最近我尝试通过添加react-i18next 和i18next 来添加国际化和本地化。
只需按照https://react.i18next.com 上提供的分步指南并添加我的翻译文件。
但是当我运行项目时,我得到控制台错误GET https://localhost:8080/locales/en/generic.json 404 (Not Found)
一开始我以为项目少了一个json-loader所以我加了webpack.config.js,结果还是一样。我检查了路径,一切似乎都正常。
提前致谢
i18n 文件
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;
根文件
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'))
附加内容
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"
]
}
【问题讨论】:
标签: javascript reactjs typescript webpack react-i18next