In the case you are given an XLIFF file from your translation service and would like to convert it to resource files that can be utilized by your javascript application utilizing i18next.
The following piece of javascript can be used as a build step for your node project. In my case it runs in a react application and is set to run with the command npm run build:resources
by adding build:resources
to the script
secion of our project's package.json. This utilizes and follows file location conventions from the i18next-http-backend library.
const fs = require('fs');
const xliff = require('xliff')
function writeFileCallback(err,data) {
if (err) {
return console.log(err);
}
console.log(data);
}
function writeTranslationFile(dir, content){
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, {
recursive: true
});
}
fs.writeFile(`${dir}/translation.json`, JSON.stringify(content), writeFileCallback);
}
function createResources() {
console.log(`Getting XLF file from directory ${process.cwd()}`);
let xml_string = fs.readFileSync("./src/locales/raw/example.fr.xlf", "utf8")
console.log(xml_string);
console.log("Converting xml to js")
xliff.xliff2js(xml_string, (err, res) => {
console.log("Converted xml to js")
console.log(JSON.stringify(res))
const en = xliff.sourceOfjs(res)
const fr = xliff.targetOfjs(res);
console.log("writing files")
writeTranslationFile("./public/locales/en", en);
writeTranslationFile("./public/locales/fr", fr);
});
}
createResources();