// 1.Flattens messages extracted via the React Intl Babel plugin. An error will be // thrown if there are messages with the same `id`. The result is a file containing // `id: message` pairs in "en" locale. // // 2. Takes all translations and groups them into a single file. var fs = require('fs'); var path = require('path'); var globSync = require('glob').sync; var mkdirpSync = require('mkdirp').sync; const MESSAGES_PATTERN = './src/i18n/src/**/*.json'; const LANG_DIR = './src/i18n/'; const LANG_PATTERN = './src/i18n/*.json'; const FINAL_FILE = './src/messages.json'; // Read message files generated by react-intl-babel-plugin. let messages = globSync(MESSAGES_PATTERN) .map((filename) => fs.readFileSync(filename, 'utf8')) .map((file) => JSON.parse(file)) .reduce((collection, descriptors) => { descriptors.forEach(({id, defaultMessage}) => { if (collection.hasOwnProperty(id)) { throw new Error(`Duplicate message id: ${id}`); } collection[id] = defaultMessage; }); return collection; }, {}); // Write English translation. let filename = path.join(LANG_DIR, 'en.json'); mkdirpSync(path.dirname(filename)); fs.writeFileSync(filename, JSON.stringify(messages, null, 2)); // Read all translations. messages = globSync(LANG_PATTERN) .map((filename) => { const parts = filename.split('/'); const locale = parts[parts.length - 1].split('.json')[0]; return { [locale]: JSON.parse(fs.readFileSync(filename, 'utf8')) }; }) .reduce((collection, descriptors) => { return { ...collection, ...descriptors }; }, {}); // Write file with all translations combined. mkdirpSync(path.dirname(FINAL_FILE)); fs.writeFileSync(FINAL_FILE, JSON.stringify(messages, null, 2));