ngx-translate | | Find unused/misplaced translation strings | Search

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.

Cell 0

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

What the code could have been:

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

Module Overview

This Node.js module provides a function getTranslations that extracts translation keys and values from HTML files in a project directory.

Function Signature

function getTranslations(project) {... }

Function Parameters

Function Flow

  1. Use the glob module to find all component.html files in the project directory, excluding files under temp-demo-pages.
  2. For each file, read the contents as a string using fs.readFileSync.
  3. Use a regular expression (translateRegex) to find all translation strings in the HTML file.
  4. Extract the translation key (filename with modifications) and value (translation string).
  5. Create an object with the translation key and value.
  6. Collect all translation objects into an array.
  7. Reduce the array to a single object with a flat structure.

Returning Value

The function returns an object with translation keys as properties and arrays of translation values as values.

Example Usage

var getTranslations = require('./getTranslations');
var cwd = '/Users/briancullinan/Documents/portal/src/';
var translations = getTranslations(cwd);
console.log(translations);