Skip to content

Instantly share code, notes, and snippets.

@michaelkrog
Last active October 5, 2024 06:28
Show Gist options
  • Save michaelkrog/7aeca3121c341c82546311742056e09a to your computer and use it in GitHub Desktop.
Save michaelkrog/7aeca3121c341c82546311742056e09a to your computer and use it in GitHub Desktop.
Xliff to Json (buildtime)
import {xliff12ToJs} from 'xliff';
import {readFileSync, writeFileSync} from 'fs';
export async function xliffToJson(translations) {
const parserResult = await xliff12ToJs(translations, {
captureSpacesBetweenElements: true,
});
const xliffContent = parserResult.resources["ng2.template"];
return Object.keys(xliffContent).reduce((result, current) => {
const translation = xliffContent[current].target;
if (typeof translation === "string") {
result[current] = translation.trim();
} else if (Array.isArray(translation)) {
result[current] = translation
.map((entry) =>
typeof entry === "string" ? entry.trim() : `{{${entry.Standalone.id}}}`,
)
.map((entry) => entry.replace("{{", "{$").replace("}}", "}").trim())
.join(" ").trim();
} else {
throw new Error("Could not parse XLIFF: " + JSON.stringify(translation));
}
return result;
}, {});
}
['da', 'fr', 'de', 'nb', 'sv'].forEach(async lang => {
const xliffFile = `src/i18n/messages.${lang}.xlf`;
const jsonFile = `src/i18n/messages.${lang}.json`;
const xliff = readFileSync(xliffFile, 'utf8');
const js = await xliffToJson(xliff);
writeFileSync(jsonFile, JSON.stringify(js));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment