Created
May 23, 2025 13:59
-
-
Save johnkegd/5674538e90d868385bfdc8da97655940 to your computer and use it in GitHub Desktop.
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
| /* | |
| * xlf-to-json-source.js | |
| * | |
| * Convert an Angular XLF (XLIFF) file to a flat JSON file for use with ngx-translate. | |
| * Extracts all <trans-unit> keys and their <source> text as key-value pairs. | |
| * | |
| * Requirements: | |
| * - Node.js (any modern version) | |
| * - jsdom npm package (install with: npm install jsdom) | |
| * | |
| * Usage: | |
| * node xlf-to-json-source.js path/to/messages.xlf path/to/output.json | |
| * | |
| * Example: | |
| * node xlf-to-json-source.js src/assets/i18n/messages.en.xlf src/assets/i18n/en.json | |
| * node xlf-to-json-source.js src/assets/i18n/messages.de.xlf src/assets/i18n/de.json | |
| * | |
| * This script will create a flat JSON file with all translation keys at the root. | |
| * | |
| * For extracting <target> translations (for non-source languages), modify the script to use: | |
| * const target = unit.querySelector('target')?.textContent?.trim(); | |
| * if (id && target) { result[id] = target; } | |
| */ | |
| const fs = require('fs'); | |
| const { JSDOM } = require('jsdom'); | |
| const origin = "target"; | |
| if (process.argv.length < 4) { | |
| console.error('Usage: node xlf-to-json-source.js path/to/messages.xlf path/to/output.json'); | |
| process.exit(1); | |
| } | |
| const xlfFile = process.argv[2]; | |
| const outFile = process.argv[3]; | |
| const xlf = fs.readFileSync(xlfFile, 'utf8'); | |
| const dom = new JSDOM(xlf, { contentType: 'text/xml' }); | |
| const transUnits = dom.window.document.querySelectorAll('trans-unit'); | |
| const result = {}; | |
| transUnits.forEach(unit => { | |
| const id = unit.getAttribute('id'); | |
| const source = unit.querySelector('target')?.textContent?.trim(); | |
| if (id && source) { | |
| result[id] = source; | |
| } | |
| }); | |
| fs.writeFileSync(outFile, JSON.stringify(result, null, 2)); | |
| console.log(`Wrote ${Object.keys(result).length} keys to ${outFile}`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment