Skip to content

Instantly share code, notes, and snippets.

@mrcunninghamz
Last active January 22, 2024 08:47
Show Gist options
  • Save mrcunninghamz/09ca59d5ac2d8876da54e4d8fe2ab94d to your computer and use it in GitHub Desktop.
Save mrcunninghamz/09ca59d5ac2d8876da54e4d8fe2ab94d to your computer and use it in GitHub Desktop.
XLIFF to lazy loaded resource files for i18next

Abstract

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.

Notes

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.

Code

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();

Example project

react-localization-example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment