How to become global but sell locally? This is the same question of any international businesses. The very first thing to do is eliminating the language barrier. Translation helps Magento 2 store owners localize their websites to their customers. Displayed in the native language of the visitors, your website will be more friendly and fit with the local market.

You might know that in Magento 2, you can call __('to be translated') function to translate any string in any PHP file, but this function can’t be used in JS files. 

Don't worry because we will guide you on how to translate strings in a javascript file in this article.

Prepare translation files

I use this module: app/code/Magenest/JsTranslate (which I have prepared all the required files before) to show you how to translate a string in a js file in Magento 2.

Make sure that you have a simple module created.

First, all translation files in your module are located in the “i18n” folder under your app/code/<vendor>/<module>/ directory.

Create an en_US.csv file in the “i18n” folder, and its name has to match with your locale code (e.g: en_US for the US, en_GB for GB, fr_CA for French Canada,...) in your Magento store.

For example, if your locale is French (Canada), then the name of CSV file must be fr_CA.csv, or English (United States) - en_US.csv

After that, put this below content to your new CSV file.

"Test","This is JS Test"

"Not","This is not Test"

Translate in a normal js file

At this step, you need to create test-jstranslate.js file in app/code/Magenest/JsTranslate/view/frontend/web/js and add these codes to your js file:

require(['jquery','mage/translate'],function ($) {
  'use strict';
   alert($.mage.__('Test'));
});

According to the above codes, Magento 2 uses mage/translate component for translating any string in a normal js file. You must call $.mage.__() function to use the component.

There is another quick alternative to this function. If you find $.mage.__() is too long then you can use $t() function (Remember to pass $t as a dependency placeholder for mage/translate)

require(['jquery','mage/translate'],function ($, $t) {
  'use strict';
   alert($t('Test'));
});

After that, add that js file to any template which we need to translate.

For example,

app/code/Magenest/JsTranslate/view/frontend/layout/magenest_index_index.xml

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
   <body>
       <block name=”test-normal-js-translate” 
template ="Magenest_JsTranslate::normalJsTranslate.phtml"/>
   </body>
</page>

app/code/Magenest/JsTranslate/view/frontend/templates/normalJsTranslate.phtml

<script type="text/x-magento-init">
   {
       "head": {
           "Magenest_JsTranslate/js/test-jstranslate": {}
       }
   }
</script>

Then, 

  • Clear cache
  • Delete file js-translation.json in pub folder 
  • Remove the browser’s cache in browser local storage (include mage-translation-file-version and mage-translation-storage ).
  • Reload page.

Translate in knockout js component

In this section, the translation method is different from the first one, because the translation will execute in file html, template of knockout js component.

To begin, let's create a test-knockout-translate.js file in app/code/Magenest/JsTranslate/view/frontend/web/js for this section and copy the following codes to it:

define(['jquery', 'uiComponent', 'ko'], function ($,Component,ko) {
   "use strict";
   return Component.extend({
       defaults: {
           template: 'Magenest_JsTranslate/test-knockout-translate'
       },

       initialize: function () {
           this._super();
       }
   });
});

Then, create a test-knockout-translate.html template file in app/code/Magenest/JsTranslate/view/frontend/web/template, this template is declared in the above js file ( template: 'Magenest_JsTranslate/test-knockout-translate' ). After creating, you have to copy the below codes to your html file:

<div class="component-wrapper">
   <div data-bind="i18n: 'Not'"></div>
</div>

In the data-bind attribute, the “i18n” is where you place the string you want to translate.

Or you can use virtual binding that also comes with knouckout.js:

<div class="component-wrapper">
   <!-- ko i18n: ‘Not’ -->
   <!-- /ko -->
</div>

In addition to data-bind attribute in knockout.js, Magento also introduces a new binding attribute that is translate for you to use in html templates:

<div class="component-wrapper">
   <div translate="'Not'"></div>
</div>

Lastly, a phtml file is needed to created to show your test. 

app/code/Magenest/JsTranslate/view/frontend/template/translate.phtml

<div id="custom-component" data-bind="scope:'customcomponent'">
   <!-- ko template: getTemplate() --><!-- /ko -->
   <script type="text/x-magento-init">
   {
       "#custom-component": {
           "Magento_Ui/js/core/app": {
              "components": {
                   "customcomponent": {
                       "component": "Magenest_JsTranslate/js/test-knockout-translate"
                   }
               }
           }
       }
   }
   </script>
</div>

And add the phtml file to your layout.

app/code/Magenest/JsTranslate/view/frontend/layout/magenest_index_index.xml

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
   <body>
       <referenceContainer name="content">
           <block name="test-js-translate" template="Magenest_JsTranslate::translate.phtml"/>
       </referenceContainer>
   </body>
</page>

When everything is done we need to clear cache as we’ve done above. Clear magento translate cache (php bin/magento cache:flush translate), remove js-translation.json and remove mage-translation-file-version and mage-translation-storage key in Browser’s local storage.

Remember that you need to change your locale in Stores -> Configuration -> General -> Locale Options -> Locale to see the expected result. For example, if you are working on fr_FR.csv file, then the French (France) locale must be selected.

Good luck and happy coding!