Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

react-intl-translations-manager integration example #19

Closed
croes opened this issue Mar 14, 2018 · 1 comment
Closed

react-intl-translations-manager integration example #19

croes opened this issue Mar 14, 2018 · 1 comment

Comments

@croes
Copy link

croes commented Mar 14, 2018

Hi,

I just wanted to share an example integration with react-intl-translations-manager.

While it's not rocket science, I think it might be useful for others that are figuring out how to integrate
react-intl in their TypeScript project. A lot of guides mention babel-plugin-react-intl, but I can't use that as I'm not using Babel, or compiling to ES6. Using typescript-react-intl is a lot easier. I still want to manage my translations with react-intl-translations-manager though.

In short, the following approach is used:

  1. all messages are extracted using typescript-react-intl, and written to a temporary allMessages.json file.
  2. react-intl-translations-manager uses this allMessages.json file to manage the translations in src/translations.
  3. The temp file is cleaned up.

Dependencies:

The script (scripts/manageTranslations.js):

const DEFAULT_LANGUAGE = 'en-US'; // for the default language, everything is automatically whitelisted
const LANGUAGES = ['nl-BE', 'fr-BE']; // translations to generate---don't include the default language
const TARGET_DIRECTORY = 'src/translations';
const EXTRACT_MESSAGE_FILE_PATTERN = 'src/**/*.@(tsx|ts)';

const TEMP_DIR = './temp';
const TEMP_MESSAGE_FILENAME = 'allMessages.json';

const fs = require('fs');
const path = require('path');
const glob = require('glob');
const rimraf = require('rimraf');
const parser = require('typescript-react-intl').default;
const manageTranslations = require('react-intl-translations-manager').default;
const {readMessageFiles, getDefaultMessages} = require('react-intl-translations-manager');

function extractTranslations(pattern, cb) {
  let results = [];
  pattern = pattern || 'src/**/*.@(tsx|ts)';
  glob(pattern, function (err, files) {
    if (err) {
      throw new Error(err);
    }
    files.forEach(function(f) {
      const contents = fs.readFileSync(f).toString();
      const res = parser(contents);
      results = results.concat(res);
    });

    cb && cb(results);
  });
}

if (!fs.existsSync(TEMP_DIR)){
  fs.mkdirSync(TEMP_DIR);
}

const tempMessageFilePath = path.join(TEMP_DIR, TEMP_MESSAGE_FILENAME);

extractTranslations(EXTRACT_MESSAGE_FILE_PATTERN, function (messages) {
  fs.writeFileSync(tempMessageFilePath, JSON.stringify(messages, null, 2));

  manageTranslations({
    messagesDirectory: TEMP_DIR,
    translationsDirectory: TARGET_DIRECTORY,
    languages: [DEFAULT_LANGUAGE, ...LANGUAGES],
    // avoid reporting translation issues with default language - https://github.com/GertjanReynaert/react-intl-translations-manager/issues/76
    overrideCoreMethods: {
      provideWhitelistFile: (language) => {
        // Avoid reporting untranslated stuff in defaultLanguage
        if (language.lang === DEFAULT_LANGUAGE) {
          const messageFiles = readMessageFiles(TEMP_DIR);
          const messages = getDefaultMessages(messageFiles).messages;
          return Object.keys(messages);
        } else {
          if (!fs.existsSync(language.whitelistFilepath)) {
            return [];
          }
          return JSON.parse(fs.readFileSync(language.whitelistFilepath, 'utf-8'));
        }
      }
    }
  });

  rimraf.sync(TEMP_DIR);
});

For convenience, you can add this to your npm scripts:

"manage:translations": "node scripts/manageTranslations.js",

Hope this helps someone!

@BANG88
Copy link
Owner

BANG88 commented Mar 15, 2018

Thank you for sharing this approach.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants