How to define messages with react-i18next

Viewed 297

I'd like to ask a question about whether react-i18next provides us a way to define messages as react-intl

I wanna define all my messages first then using i18next-scanner to extract to json file.

Thanks in advance for your help in this matter.

1 Answers

After a while of researching. I'd give my way to someone wanna define messages in such a messages.js. BTW, I'm using i18nxt-scanner to extract the messages to JSON file.

i18next-scanner.config.js

module.exports = {
  input: [
    'src/app/**/*.{js,jsx}',
    // Use ! to filter out files or directories
    '!app/**/*.spec.{js,jsx}',
    '!app/i18n/**',
    '!**/node_modules/**',
  ],
  output: './',
  options: {
    debug: true,
    removeUnusedKeys: true,
    func: {
      list: ['getTranslationId'],
      extensions: ['.js', '.tsx'],
    },
    lngs: ['en', 'ko'],
    ns: ['translation'],
    defaultLng: 'en',
    defaultNs: 'translation',
    defaultValue: '',
    resource: {
      loadPath: 'src/locales/{{lng}}/{{ns}}.json',
      savePath: 'src/locales/{{lng}}/{{ns}}.json',
      jsonIndent: 2,
      lineEnding: '\n',
    },
    nsSeparator: false, // namespace separator
    keySeparator: false, // key separator
    interpolation: {
      prefix: '{{',
      suffix: '}}',
    },
  },
};

messages.js

import { getTranslationId } from 'locales/utils';

const messages = {
  title: getTranslationId('Homepage_title', {
    defaultValue: 'hello, {{name}}',
  }),
  count: getTranslationId('Homepage_count', {
    defaultValue: '{{count}} time',
    count: 0, // for plurals
  }),
};

export default messages;

locales/utils.js

export const getTranslationId = id => {
  if (!id || !id.includes('_'))
    throw new Error('ID pattern should be "BLOCK_ElEMENT"');
  return id;
};

Extracting command

yarn run i18next-scanner

Hope this helps! :D

Related