2018-03-07 07:42:14 +00:00
|
|
|
const i18next = require('i18next')
|
2017-07-16 20:19:45 +00:00
|
|
|
const XHR = require('i18next-xhr-backend')
|
|
|
|
const LanguageDetector = require('i18next-browser-languagedetector')
|
|
|
|
|
|
|
|
const options = {
|
|
|
|
fallbackLng: 'en',
|
|
|
|
load: 'languageOnly', // we only provide en, de -> no region specific locals like en-US, de-DE
|
|
|
|
|
|
|
|
// have a common namespace used around the full app
|
|
|
|
ns: ['common'],
|
|
|
|
defaultNS: 'common',
|
|
|
|
|
|
|
|
debug: true,
|
|
|
|
saveMissing: true,
|
|
|
|
|
|
|
|
interpolation: {
|
|
|
|
escapeValue: false, // not needed for react!!
|
|
|
|
formatSeparator: ',',
|
|
|
|
format: (value, format, lng) => {
|
|
|
|
if (format === 'uppercase') return value.toUpperCase()
|
|
|
|
return value
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-03-07 07:42:14 +00:00
|
|
|
const i18nInstance = i18next
|
|
|
|
|
2017-07-16 20:19:45 +00:00
|
|
|
// for browser use xhr backend to load translations and browser lng detector
|
|
|
|
if (process.browser) {
|
2018-03-07 07:42:14 +00:00
|
|
|
i18nInstance
|
2017-07-16 20:19:45 +00:00
|
|
|
.use(XHR)
|
|
|
|
// .use(Cache)
|
|
|
|
.use(LanguageDetector)
|
|
|
|
}
|
|
|
|
|
|
|
|
// initialize if not already initialized
|
2018-03-07 07:42:14 +00:00
|
|
|
if (!i18nInstance.isInitialized) i18nInstance.init(options)
|
2017-07-16 20:19:45 +00:00
|
|
|
|
|
|
|
// a simple helper to getInitialProps passed on loaded i18n data
|
2018-03-07 07:42:14 +00:00
|
|
|
const getInitialProps = (req, namespaces) => {
|
|
|
|
if (!namespaces) namespaces = i18nInstance.options.defaultNS
|
2017-07-16 20:19:45 +00:00
|
|
|
if (typeof namespaces === 'string') namespaces = [namespaces]
|
|
|
|
|
|
|
|
req.i18n.toJSON = () => null // do not serialize i18next instance and send to client
|
|
|
|
|
|
|
|
const initialI18nStore = {}
|
|
|
|
req.i18n.languages.forEach((l) => {
|
|
|
|
initialI18nStore[l] = {}
|
|
|
|
namespaces.forEach((ns) => {
|
2018-03-06 09:39:35 +00:00
|
|
|
initialI18nStore[l][ns] = (req.i18n.services.resourceStore.data[l] || {})[ns] || {}
|
2017-07-16 20:19:45 +00:00
|
|
|
})
|
|
|
|
})
|
|
|
|
|
|
|
|
return {
|
|
|
|
i18n: req.i18n, // use the instance on req - fixed language on request (avoid issues in race conditions with lngs of different users)
|
|
|
|
initialI18nStore,
|
|
|
|
initialLanguage: req.i18n.language
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-03-07 07:42:14 +00:00
|
|
|
module.exports = {
|
|
|
|
getInitialProps,
|
|
|
|
i18nInstance,
|
|
|
|
I18n: i18next.default
|
|
|
|
}
|