The Node.js module getTranslations
extracts translation keys and values from HTML files in a specified project directory, returning an object with flat translation keys as properties and arrays of values as values. The function uses glob
to find HTML files, regular expressions to extract translations, and reduces the results into a single object for ease of use.
var glob = require('glob');
var translateRegex = (/[\{"]([^><"]*?)\s*\|\s*translate\s*(:\s*[^><"\}]*?)?["\}]/ig);
function getTranslations(project) {
var files = glob.sync('**/*component.html', {
ignore: '**/temp-demo-pages/**',
cwd: project
});
var translations = files.map((f, i) => {
var html = fs.readFileSync(path.join(cwd, f)).toString();
let r;
var translateStrings = [];
while ((r = translateRegex.exec(html)) !== null) {
translateStrings[translateStrings.length] = r[1].trim().replace(/[\'{}\s]/ig, '');
}
var desiredKey = f
.replace('app/', '')
.replace(/\//ig, '.')
.replace('.component.html', '')
.replace(/-/ig, '').split('.');
desiredKey.pop();
desiredKey = desiredKey.join('.').toUpperCase();
var result = {};
result[desiredKey] = translateStrings;
return result;
});
var translationKeys = translations.reduce((obj, tr) => {
var key = Object.keys(tr).pop();
if (typeof obj[key] !== 'undefined') {
obj[key] = obj[key].concat(tr[key]);
} else {
obj[key] = tr[key];
}
return obj;
}, {});
return translationKeys;
}
module.exports = getTranslations;
if(typeof $ !== 'undefined') {
var cwd = '/Users/briancullinan/Documents/portal/src/';
getTranslations(cwd);
}
const glob = require('glob-promise');
const path = require('path');
const fs = require('fs');
const console = require('console');
// Regular expression to match translate keys in HTML files
const translateRegex = /{([\w\s]+?)\s*\|\s*translate\s*(:\s*[\w\s]+?)?}/gi;
/**
* Extracts translation keys from HTML component files in a project.
*
* @param {string} project - Path to the project directory.
* @returns {object} - An object containing translation keys as properties and their corresponding values as arrays.
*/
async function getTranslations(project) {
try {
// Get HTML component files in the project, ignoring temp-demo-pages directory
const files = await glob(`**/component.html`, { cwd: project, ignore: '**/temp-demo-pages/**' });
// Initialize an object to store translation keys
const translationKeys = {};
// Loop through each file and extract translation keys
for (const file of files) {
// Read the contents of the file
const html = await fs.promises.readFile(path.join(project, file), 'utf8');
// Use regular expression to match translate keys in the HTML file
const matches = html.match(translateRegex);
if (matches) {
// Extract the translate key and text from each match
const translateStrings = matches.map((match) => {
// Remove curly brackets and any whitespace characters
const key = match.replace(/\{|\}/g, '').trim();
return key;
});
// Determine the desired key for the translations object
const desiredKey = file
.replace('app/', '')
.replace(/\//ig, '.')
.replace('.component.html', '')
.replace(/-/ig, '')
.split('.')
.filter((_, i) => i!== 0)
.join('.');
// Add the translations to the translations object
if (!translationKeys[desiredKey]) {
translationKeys[desiredKey] = [];
}
translationKeys[desiredKey].push(...translateStrings);
}
}
// Return the translations object
return translationKeys;
} catch (error) {
console.error(error);
return {};
}
}
module.exports = getTranslations;
// Example usage
if (typeof $!== 'undefined') {
const cwd = '/Users/briancullinan/Documents/portal/src/';
getTranslations(cwd).then((translations) => console.log(translations));
}
This Node.js module provides a function getTranslations
that extracts translation keys and values from HTML files in a project directory.
function getTranslations(project) {... }
project
: The project directory path.glob
module to find all component.html
files in the project directory, excluding files under temp-demo-pages
.fs.readFileSync
.translateRegex
) to find all translation strings in the HTML file.The function returns an object with translation keys as properties and arrays of translation values as values.
var getTranslations = require('./getTranslations');
var cwd = '/Users/briancullinan/Documents/portal/src/';
var translations = getTranslations(cwd);
console.log(translations);