Use i18next with XHR backend in client-side javascript












0















The documentation at i18next-xhr-backend tells me to use import to load their module. But when I use the import-statement, nothing happens and Firefox gives me a SyntaxError in the developer console:



SyntaxError: import declarations may only appear at top level of a module


So how can I use i18next library with the XHR-backend? The following code example works if the .use(XHR)-line and the corresponding import is commented out (Warning: i18next::backendConnector: No backend was added via i18next.use. Will not load resources.). But it fails, if it is not: ReferenceError: XHR is not defined



//import Fetch from 'i18next-fetch-backend';

let t = null;

i18next
.use(XHR)
.init({
debug: true,
fallbackLng: ['en'],
preload: ['en'],
ns: 'translation',
defaultNS: 'translation',
keySeparator: false, // Allow usage of dots in keys
nsSeparator: false,
backend: {
loadPath: '/locales/{{lng}}/{{ns}}.json',
},
}, (err, _t) => {
if (err) {
reject(err);
return;
}

t = _t;
//resolve();
});

jqueryI18next.init(i18next, $, {
tName: 't', // --> appends $.t = i18next.t
i18nName: 'i18n', // --> appends $.i18n = i18next
handleName: 'localize', // --> appends $(selector).localize(opts);
selectorAttr: 'data-i18n', // selector for translating elements
targetAttr: 'i18n-target', // data-() attribute to grab target element to translate (if different than itself)
optionsAttr: 'i18n-options', // data-() attribute that contains options, will load/set if useOptionsAttr = true
useOptionsAttr: false, // see optionsAttr
parseDefaultValueFromContent: true // parses default values from content ele.val or ele.text
});
$(".nav").localize();









share|improve this question



























    0















    The documentation at i18next-xhr-backend tells me to use import to load their module. But when I use the import-statement, nothing happens and Firefox gives me a SyntaxError in the developer console:



    SyntaxError: import declarations may only appear at top level of a module


    So how can I use i18next library with the XHR-backend? The following code example works if the .use(XHR)-line and the corresponding import is commented out (Warning: i18next::backendConnector: No backend was added via i18next.use. Will not load resources.). But it fails, if it is not: ReferenceError: XHR is not defined



    //import Fetch from 'i18next-fetch-backend';

    let t = null;

    i18next
    .use(XHR)
    .init({
    debug: true,
    fallbackLng: ['en'],
    preload: ['en'],
    ns: 'translation',
    defaultNS: 'translation',
    keySeparator: false, // Allow usage of dots in keys
    nsSeparator: false,
    backend: {
    loadPath: '/locales/{{lng}}/{{ns}}.json',
    },
    }, (err, _t) => {
    if (err) {
    reject(err);
    return;
    }

    t = _t;
    //resolve();
    });

    jqueryI18next.init(i18next, $, {
    tName: 't', // --> appends $.t = i18next.t
    i18nName: 'i18n', // --> appends $.i18n = i18next
    handleName: 'localize', // --> appends $(selector).localize(opts);
    selectorAttr: 'data-i18n', // selector for translating elements
    targetAttr: 'i18n-target', // data-() attribute to grab target element to translate (if different than itself)
    optionsAttr: 'i18n-options', // data-() attribute that contains options, will load/set if useOptionsAttr = true
    useOptionsAttr: false, // see optionsAttr
    parseDefaultValueFromContent: true // parses default values from content ele.val or ele.text
    });
    $(".nav").localize();









    share|improve this question

























      0












      0








      0








      The documentation at i18next-xhr-backend tells me to use import to load their module. But when I use the import-statement, nothing happens and Firefox gives me a SyntaxError in the developer console:



      SyntaxError: import declarations may only appear at top level of a module


      So how can I use i18next library with the XHR-backend? The following code example works if the .use(XHR)-line and the corresponding import is commented out (Warning: i18next::backendConnector: No backend was added via i18next.use. Will not load resources.). But it fails, if it is not: ReferenceError: XHR is not defined



      //import Fetch from 'i18next-fetch-backend';

      let t = null;

      i18next
      .use(XHR)
      .init({
      debug: true,
      fallbackLng: ['en'],
      preload: ['en'],
      ns: 'translation',
      defaultNS: 'translation',
      keySeparator: false, // Allow usage of dots in keys
      nsSeparator: false,
      backend: {
      loadPath: '/locales/{{lng}}/{{ns}}.json',
      },
      }, (err, _t) => {
      if (err) {
      reject(err);
      return;
      }

      t = _t;
      //resolve();
      });

      jqueryI18next.init(i18next, $, {
      tName: 't', // --> appends $.t = i18next.t
      i18nName: 'i18n', // --> appends $.i18n = i18next
      handleName: 'localize', // --> appends $(selector).localize(opts);
      selectorAttr: 'data-i18n', // selector for translating elements
      targetAttr: 'i18n-target', // data-() attribute to grab target element to translate (if different than itself)
      optionsAttr: 'i18n-options', // data-() attribute that contains options, will load/set if useOptionsAttr = true
      useOptionsAttr: false, // see optionsAttr
      parseDefaultValueFromContent: true // parses default values from content ele.val or ele.text
      });
      $(".nav").localize();









      share|improve this question














      The documentation at i18next-xhr-backend tells me to use import to load their module. But when I use the import-statement, nothing happens and Firefox gives me a SyntaxError in the developer console:



      SyntaxError: import declarations may only appear at top level of a module


      So how can I use i18next library with the XHR-backend? The following code example works if the .use(XHR)-line and the corresponding import is commented out (Warning: i18next::backendConnector: No backend was added via i18next.use. Will not load resources.). But it fails, if it is not: ReferenceError: XHR is not defined



      //import Fetch from 'i18next-fetch-backend';

      let t = null;

      i18next
      .use(XHR)
      .init({
      debug: true,
      fallbackLng: ['en'],
      preload: ['en'],
      ns: 'translation',
      defaultNS: 'translation',
      keySeparator: false, // Allow usage of dots in keys
      nsSeparator: false,
      backend: {
      loadPath: '/locales/{{lng}}/{{ns}}.json',
      },
      }, (err, _t) => {
      if (err) {
      reject(err);
      return;
      }

      t = _t;
      //resolve();
      });

      jqueryI18next.init(i18next, $, {
      tName: 't', // --> appends $.t = i18next.t
      i18nName: 'i18n', // --> appends $.i18n = i18next
      handleName: 'localize', // --> appends $(selector).localize(opts);
      selectorAttr: 'data-i18n', // selector for translating elements
      targetAttr: 'i18n-target', // data-() attribute to grab target element to translate (if different than itself)
      optionsAttr: 'i18n-options', // data-() attribute that contains options, will load/set if useOptionsAttr = true
      useOptionsAttr: false, // see optionsAttr
      parseDefaultValueFromContent: true // parses default values from content ele.val or ele.text
      });
      $(".nav").localize();






      javascript import internationalization i18next






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jan 2 at 1:45









      LukeLRLukeLR

      3521416




      3521416
























          1 Answer
          1






          active

          oldest

          votes


















          0














          I needed to use i18nextXHRBackend instead of just XHR, since that is the name the class gets loaded as if no loader is used. As the README.md says:




          If you don't use a module loader it will be added to window.i18nextXHRBackend




          I didn't see that before, and I didn't know that this will happen automatically, but it seems that you have to find that out on your own if not using a module loader. Lesson learned, hopefully this will help some other newbies being stuck on how to use modules in javascript. Therefore, my complete localisation.js looks like this:



          $(document).ready(function() {
          i18next
          .use(i18nextXHRBackend)
          .use(i18nextBrowserLanguageDetector)
          .init({
          debug: true,
          backend: {
          loadPath: 'locales/{{lng}}/{{ns}}.json',
          addPath: 'locales/add/{{lng}}/{{ns}}'
          }
          }, function(err, t) {
          jqueryI18next.init(i18next, $);
          $('.translatable').localize();
          $('.language-button').click(function() {
          i18next.changeLanguage(this.firstElementChild.alt).then(function(t) {
          $('.translatable').localize();
          $('#signupPassword').pwstrength("forceUpdate");
          $('#signupPasswordConfirm').pwstrength("forceUpdate");
          });
          });
          });
          });





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54000353%2fuse-i18next-with-xhr-backend-in-client-side-javascript%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            I needed to use i18nextXHRBackend instead of just XHR, since that is the name the class gets loaded as if no loader is used. As the README.md says:




            If you don't use a module loader it will be added to window.i18nextXHRBackend




            I didn't see that before, and I didn't know that this will happen automatically, but it seems that you have to find that out on your own if not using a module loader. Lesson learned, hopefully this will help some other newbies being stuck on how to use modules in javascript. Therefore, my complete localisation.js looks like this:



            $(document).ready(function() {
            i18next
            .use(i18nextXHRBackend)
            .use(i18nextBrowserLanguageDetector)
            .init({
            debug: true,
            backend: {
            loadPath: 'locales/{{lng}}/{{ns}}.json',
            addPath: 'locales/add/{{lng}}/{{ns}}'
            }
            }, function(err, t) {
            jqueryI18next.init(i18next, $);
            $('.translatable').localize();
            $('.language-button').click(function() {
            i18next.changeLanguage(this.firstElementChild.alt).then(function(t) {
            $('.translatable').localize();
            $('#signupPassword').pwstrength("forceUpdate");
            $('#signupPasswordConfirm').pwstrength("forceUpdate");
            });
            });
            });
            });





            share|improve this answer




























              0














              I needed to use i18nextXHRBackend instead of just XHR, since that is the name the class gets loaded as if no loader is used. As the README.md says:




              If you don't use a module loader it will be added to window.i18nextXHRBackend




              I didn't see that before, and I didn't know that this will happen automatically, but it seems that you have to find that out on your own if not using a module loader. Lesson learned, hopefully this will help some other newbies being stuck on how to use modules in javascript. Therefore, my complete localisation.js looks like this:



              $(document).ready(function() {
              i18next
              .use(i18nextXHRBackend)
              .use(i18nextBrowserLanguageDetector)
              .init({
              debug: true,
              backend: {
              loadPath: 'locales/{{lng}}/{{ns}}.json',
              addPath: 'locales/add/{{lng}}/{{ns}}'
              }
              }, function(err, t) {
              jqueryI18next.init(i18next, $);
              $('.translatable').localize();
              $('.language-button').click(function() {
              i18next.changeLanguage(this.firstElementChild.alt).then(function(t) {
              $('.translatable').localize();
              $('#signupPassword').pwstrength("forceUpdate");
              $('#signupPasswordConfirm').pwstrength("forceUpdate");
              });
              });
              });
              });





              share|improve this answer


























                0












                0








                0







                I needed to use i18nextXHRBackend instead of just XHR, since that is the name the class gets loaded as if no loader is used. As the README.md says:




                If you don't use a module loader it will be added to window.i18nextXHRBackend




                I didn't see that before, and I didn't know that this will happen automatically, but it seems that you have to find that out on your own if not using a module loader. Lesson learned, hopefully this will help some other newbies being stuck on how to use modules in javascript. Therefore, my complete localisation.js looks like this:



                $(document).ready(function() {
                i18next
                .use(i18nextXHRBackend)
                .use(i18nextBrowserLanguageDetector)
                .init({
                debug: true,
                backend: {
                loadPath: 'locales/{{lng}}/{{ns}}.json',
                addPath: 'locales/add/{{lng}}/{{ns}}'
                }
                }, function(err, t) {
                jqueryI18next.init(i18next, $);
                $('.translatable').localize();
                $('.language-button').click(function() {
                i18next.changeLanguage(this.firstElementChild.alt).then(function(t) {
                $('.translatable').localize();
                $('#signupPassword').pwstrength("forceUpdate");
                $('#signupPasswordConfirm').pwstrength("forceUpdate");
                });
                });
                });
                });





                share|improve this answer













                I needed to use i18nextXHRBackend instead of just XHR, since that is the name the class gets loaded as if no loader is used. As the README.md says:




                If you don't use a module loader it will be added to window.i18nextXHRBackend




                I didn't see that before, and I didn't know that this will happen automatically, but it seems that you have to find that out on your own if not using a module loader. Lesson learned, hopefully this will help some other newbies being stuck on how to use modules in javascript. Therefore, my complete localisation.js looks like this:



                $(document).ready(function() {
                i18next
                .use(i18nextXHRBackend)
                .use(i18nextBrowserLanguageDetector)
                .init({
                debug: true,
                backend: {
                loadPath: 'locales/{{lng}}/{{ns}}.json',
                addPath: 'locales/add/{{lng}}/{{ns}}'
                }
                }, function(err, t) {
                jqueryI18next.init(i18next, $);
                $('.translatable').localize();
                $('.language-button').click(function() {
                i18next.changeLanguage(this.firstElementChild.alt).then(function(t) {
                $('.translatable').localize();
                $('#signupPassword').pwstrength("forceUpdate");
                $('#signupPasswordConfirm').pwstrength("forceUpdate");
                });
                });
                });
                });






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jan 4 at 2:30









                LukeLRLukeLR

                3521416




                3521416
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54000353%2fuse-i18next-with-xhr-backend-in-client-side-javascript%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    MongoDB - Not Authorized To Execute Command

                    in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

                    Npm cannot find a required file even through it is in the searched directory