Problem/Motivation
Translation of the frontend components in JavaScript in Drupal is pretty easy: just wrap the text by the Drupal.t() function in any place of your JS and it will work.
So, if you write JavaScript code in pure JS, and attach those JS files using Drupal API, The Drupal Locale module automatically parses these files and extracts all translateable string, and adds the translated strings to the frontend JS automatically too.
But, if you use TS or JSX, each line of your code will be transpiled to pure JS by Babel. And that Babel breaks the whole idea!
So, if we have something like Drupal.t('Hello world') in any TS or JSX file, it will be represented as something like this:
var a=require('Drupal');var myString=a.t('Hello world');
that is already not parseable.
Therefore, any attempts to parse the transpiled JS files tend to fail.
Steps to reproduce
1. Write a bit of JavaScript code like this:
const myString = Drupal.t('Hello world');
console.log(myString);and attach this file to a page.
2. Translate this string by the Drupal translation interface to another language.
3. See that the translation works automatically!
4. Convert this JS file to TypeScript and transpile it back to JS using Webpack and Babel or something else.
5. See that the automatic translation stops working.
Proposed resolution
I see several ways to fix this issue:
1. Add the source files (TS and JSX) to the parser, to make them able to extract the strings before the files get transpiled.
2. Configure Babel or something else to keep the Drupal.t() calls untouched in the transpiled JS.
Comments
Comment #2
murzAnother alternative to this issue is to not use any transpilers, but use pure JS. But with this approach, we will get a problem with missing translations in files, included from the JS side (by import, require). And a workaround for this is to include them from the Drupal side instead, something like this -
components/my-component/my-component.component.yml:And an additional benefit of including all the dependencies in the YAML file is that they get merged and compacted to one JS file using the Drupal native approach, speeding up the page load time in the browser.
Comment #3
nod_I don't see what to change in Drupal core, hence setting this as a support request.
The easiest way to go about this is exclude Drupal.t from being replaced. Using a library with attribute type: module shouldn't aggregate them so you won't get aggregation or minification for theses
Comment #5
quietone commentedI see that @nod_ has answered this support request.
Keep in mind that the Drupal Core issue queue is not the ideal place for support requests. There are several support options listed on our Support page, including the Drupal Forums and Drupal Answers. There is also Drupal Slack. You may get better replies in one of those places.
I am closing this per the guidance in Handle or refer a support request in an issue.