mardi 21 août 2018

Modify how ember-i18n localizations are loaded, split localization strings from main app.js

I am trying to modify the way ember-i18n localizations are loaded. What I want to do is have the localizations in a separate file from the main app javascript file.

Ideally, the structure would remain the same as now. So I would have app/locales/fr/translations.js and app/locales/de/translations.js , each having content similar to this:

export default {
 key: "value"
}

So I thought I need to write a custom addon, which would alter the build process. This addon would need to:

  1. Ignore app/locales from final build

  2. Compile all the translation files into one

  3. Transpile the new file with babel

  4. Copy the file in dist/assets/translations.js

The combined translation file would look something like this:

export default {
 fr: {
   key: "value"
 },
 de: {
  key: "value"
 }

This way, I would be able to use and instance initializer and simply import and use this module:

import Translations from 'my-translations';

export function initialize(instance) {
   const i18n = instance.lookup('service:i18n');
}

Also, index.html would be:

<script src="assets/vendor.js"></script>
<script src="assets/translations.js"></script>
<script src="assets/my-app.js"></script>

Well, I started writing the custom addon, but I got stuck. I managed to ignore the locales, and I wrote code that parses all the localizations, but I do not know how to write the new translations file in dist. What hook do I neeed to use, to be able to write into dist? Any help? Thank you so much.

Here is the code I wrote:

preprocessTree: function(type, tree) {
    if(type !== 'js') {return tree;}

    var treeWithoutLocales = new Funnel(tree, {
        exclude: ['**/locales/*/translations.js']
    });

    var translations = {};
    var files = fs.readdirSync('app/locales');
    files.forEach((tag) => {
        if(tag !== 'fr') {return;}
        let contents = fs.readFileSync('app/locales/' + tag + '/translations.js', 'utf8');
        contents = contents.replace(/^export default /, '');
        contents = contents.replace(/;$/, '');
        contents = JSON.parse(contents);
        translations[tag] = contents;
    });

    // Should do something with this .. how to write in dist? and when? I need it compiled with babel
    var fileTree = writeFile('/mondly-app/locales/translations.js', 'export default ' + JSON.stringify(translations) + ';');

    return treeWithoutLocales;
}




Aucun commentaire:

Enregistrer un commentaire