skip to Main Content

I have a .po file which follows the following format (keeping it slim – notice there is only a msgid and mstr as part of each set of strings):

msgid "hello everyone"
msgstr "bonjour toute la monde"

The msgid is the original text in english, and the msgstr is the translated text in french.
We are currently trying to use the library i18next-gettext-converter, but not sure how to do such a task with the library (if even possible), or if there’s a different javascript library that could meet our needs.

We would want our one large .po file to be able to generate 1 english translation and 1 french translation file so the react-i18next library can be used.

I’ve tried using the cli options with the -l and -s flags, and played around with the -K option flags, but nothing seems to even come close.

2

Answers


  1. I think you should read the .po file and write a new file as you want, without any library, here is a snippet for you to start:

    // node format.js
    const fs = require('fs');
    
    function parsePoFile(poFilePath) {
        const content = fs.readFileSync(poFilePath, 'utf8');
        const entries = content.split('nn').map(entry => {
            const lines = entry.trim().split('n');
            const msgid = lines.find(line => line.startsWith('msgid')).split('msgid ')[1];
            const msgstr = lines.find(line => line.startsWith('msgstr')).split('msgstr ')[1];
            return { msgid, msgstr };
        });
        return entries;
    }
    
    function generateTranslationFile(entries, lang) {
        const translations = entries.reduce((acc, entry) => {
            acc[entry.msgid] = entry.msgstr;
            return acc;
        }, {});
    
        fs.writeFileSync(`translations.${lang}.json`, JSON.stringify(translations, null, 2), 'utf8');
    }
    
    const poFilePath = 'your_po_file.po';
    const entries = parsePoFile(poFilePath);
    generateTranslationFile(entries, 'en'); // English translation file
    generateTranslationFile(entries, 'fr'); // French translation file
    
    
    Login or Signup to reply.
  2. I’m not sure you fully described the problem, because i18next-gettext-converter seems to do exactly what you need.

    You can use it in command line by installing it globally:

    npm install i18next-conv -g
    

    So assuming you have test.po file with content:

    msgid "hello everyone"
    msgstr "bonjour toute la monde"
    

    You can execute command:

    i18next-conv -l fr -s test.po -t test.fr.json
    

    And it will create test.fr.json for you:

    {
        "hello everyone": "bonjour toute la monde"
    }
    

    Is that what you want to achieve?

    Otherwise, please, provide a sample of source and desired result files.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search