Skip to content

Instantly share code, notes, and snippets.

@choffmeister
Last active April 29, 2018 16:52
Show Gist options
  • Save choffmeister/d8902702c8318c8a67cb1185e3a75459 to your computer and use it in GitHub Desktop.
Save choffmeister/d8902702c8318c8a67cb1185e3a75459 to your computer and use it in GitHub Desktop.
i18next-json-loader

i18next-json-loader

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.i18next\.json$/,
        use: [{ loader: path.resolve(__dirname, 'i18next-json-loader') }],
      },
    ]
  }
}

MyComponent.i18next.json

{
  "en": {
    "name": "Name",
    "age": "Age"
  },
  "de": {
    "name": "Name",
    "age": "Alter"
  }
}

MyComponent.jsx

import React from 'react'
import { I18n } from 'react-i18next'
import translations from './MyComponent.i18next.json'

export const MyComponent = () => {
  return (
    <I18n ns={translations.namespace}>
      {t => (
        <div>
          <div>{t('name')}</div>
          <div>{t('age')}</div>
        </div>
      )}
    </I18n>
  )
}
const path = require('path')
const crypto = require('crypto')
const extension = '.i18next.json'
module.exports = function(content) {
this.cacheable && this.cacheable()
this.value = content
const filename = path.basename(this.resourcePath)
const hash = crypto.createHash('sha1').update(content).digest('base64')
const namespace = filename.substr(0, filename.length - extension.length) + '__' + hash.substr(0, 5)
const translations = JSON.parse(content)
const output = `var i18next = require('i18next').default;
var translations = ${JSON.stringify(translations)};
Object.keys(translations).forEach(function(lng) {
i18next.addResourceBundle(lng, ${JSON.stringify(namespace)}, translations[lng]);
});
module.exports = {
namespace: ${JSON.stringify(namespace)},
translations: translations,
};
`
return output
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment