我想使用i18next-http-backend加载各个语言的translation.json文件,所以我将它们作为静态文件放在我的公共文件夹中,例如:public/en/translation.json。
后端插件尝试从 http://localhost:5173/locales/en/translation.json 获取,这似乎是正确的。
这是我的代码:
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import Backend from 'i18next-http-backend';
i18n
// load translation using http -> see /public/locales (i.e. https://github.com/i18next/react-i18next/tree/master/example/react/public/locales)
// learn more: https://github.com/i18next/i18next-http-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)
// init i18next
// for all options read: https://www.i18next.com/overview/configuration-options
.init({
fallbackLng: 'en',
debug: true,
load: 'languageOnly',
interpolation: {
escapeValue: false // not needed for react as it escapes by default
},
backend: {
overrideMimeType: 'application/json', // tried with this and without
loadPath: '/locales/{{lng}}/{{ns}}.json'
}
});
export default i18n;
同样位于公共文件夹内的 favicon.png 加载正常,所以我不知道 json 文件有什么问题。
我从CRA迁移到Vite后也遇到了类似的问题。 就我而言,我从不同的后端服务器获取翻译文件。问题在于获取 json 文件而不是 html。
所以我尝试使用代理,它很有帮助!尝试:
export default defineConfig({
server: {
proxy: {
'/api': {
target: SOME_URL,
changeOrigin: true,
},
},
},
})
文档:https://vitejs.dev/config/server-options.html#server-proxy