Created
September 10, 2021 11:17
-
-
Save majirosstefan/85691f68ab0cd4394a8e0d5b5cae41c9 to your computer and use it in GitHub Desktop.
This is a script to translate values in JSON values which I use to localization support for apps built in my own dev studio (stefan-majiros.com)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// follow the π for important parts | |
const {createWriteStream} = require('fs'); | |
// you need to install this lib: globally or locally | |
var TJO = require('translate-json-object')(); | |
// π feel free to use any other JSON file | |
var json_SOURCE_OF_TRUTH = require('../src/localization/translations/en.json'); | |
// array of iso codes | |
// e.g. [ 'af', 'am','az', 'be', 'bg', 'bn', 'bs', 'ca', 'co', 'cs', 'da', 'de', 'en'] | |
var supportedLanguages = require('./supportedLanguages'); | |
var fs = require('fs'); | |
var path = require('path'); | |
// π name of the folder with translated files | |
const outputDirectory = 'translations'; | |
TJO.init({ | |
// π | |
googleApiKey: '', | |
}); | |
(async function main() { | |
try { | |
const outputDirectoryPath = path.join(__dirname, outputDirectory); | |
const translationFolderExists = fs.existsSync(outputDirectoryPath); | |
if (!translationFolderExists) { | |
fs.mkdirSync(outputDirectoryPath); | |
} | |
// π | |
for (const lang of supportedLanguages) { | |
if (fileExists(lang) === false) { | |
let data = await TJO.translate(json_SOURCE_OF_TRUTH, lang); | |
writeToFile(data, lang); | |
sleep(1000); | |
} else { | |
console.log('File already exits for lang ', lang); | |
} | |
} | |
} catch (error) { | |
console.log('error ', error); | |
} | |
// π | |
console.log( | |
'Do not forget to run prettier on translations folder to make output pretty', | |
); | |
console.log('Now you can copy translations folder into app.'); | |
})(); | |
function fileExists(lang) { | |
return fs.existsSync(pathRelative(lang)); | |
} | |
function pathRelative(lang) { | |
return path.join(__dirname, outputDirectory, lang + '.json'); | |
} | |
const writeToFile = (data, lang = 'out.txt') => { | |
//TODO mkdir translation folder - if it does not exist, code fails | |
const stream = createWriteStream(pathRelative(lang)); | |
stream.once('open', function (fd) { | |
stream.write(JSON.stringify(data)); | |
stream.end(); | |
console.log('lang', lang, ' written'); | |
}); | |
}; | |
function sleep(ms = 1000) { | |
return new Promise(resolve => { | |
setTimeout(resolve, ms); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The whole article could be found here:
https://stefan-majiros.com/blog/implementing-react-native-localization-like-a-pro/