Lit-translate displays a sequence of characters instead of providing a translated text

I'm currently using lit-translate to localize my "Elmish" TypeScript website into different languages. My setup includes webpack and dotnet.

Within my index.ts file, I configure the translation like this:

registerTranslateConfig({
    lookup: (key, config) => config.strings != null ? config.strings[key] : key,
    empty: key => key,
    loader: lang => {
          return new Promise((resolve, reject) => {
            resolve({"title": "Der Titel"});
          })}   
    });

use("en");

(The loader being hardcoded is a temporary solution as fetching the localization file didn't work, but it's not crucial at the moment).

In my HTML, I utilize get("title") or translate("title") to fetch the translations. However, instead of getting the translation, I get either [title] or

(part) => { partCache.set(part, cb); updatePart(part, cb); }

If I store the result of translate() in a variable, I encounter the following error within the Object:

TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
    at Function.r (<anonymous>:1:83)
    at Module../src/index.ts (http://localhost:8080/app.bundle.js:9800:10)
    at __webpack_require__ (http://localhost:8080/app.bundle.js:12476:33)
    at http://localhost:8080/app.bundle.js:13494:11
    at http://localhost:8080/app.bundle.js:13497:12

I have attempted disabling webpack strict mode without success.

The complete class structure is shown below:

export class App extends Application<Model, Message, {}> {
  @property({type: Boolean})
  hasLoadedStrings = false;

    init(): [Model, Cmd] {
    const initModel: Model = {
      openPage: [{title: "Home"}, home]
    }

    return [initModel, Cmd.none]
  }

  constructor() {
    super();
    this.hasLoadedStrings = false;
  }

  shouldUpdate (changedProperties: Map<string | number | symbol, unknown>) {
    return this.hasLoadedStrings && super.shouldUpdate(changedProperties);
  }

  async connectedCallback () {
    super.connectedCallback();
 
    await use("en");
    this.hasLoadedStrings = true;
  }

}

customElements.define('my-element', App);

Answer №1

After encountering errors with the lit-translate package, I took matters into my own hands and created a custom translation library to solve the problem:

translate.ts:

const de_config = 
{
  "Category": {
    "Home": "Start",
  },
  "Home": {
    "Welcome back,": "Willkommen zurück,"
};

export function translate(key: string) {

    const keyParts = key.split(".");
    const keyCategory = keyParts.shift();
    const keyWord = keyParts.join('.');

    let translationIndexes = typedKeys(de_config);

    for(let translationIndex of translationIndexes)
    {
      if(translationIndex == keyCategory) {
        let translationKeys = typedKeys(de_config[translationIndex]);
        
        for(let translationKey of translationKeys) {
            if(translationKey == keyWord) {
              return de_config[translationIndex][translationKey];         
          }
        }
      }
    }
    return key;  
  }

function typedKeys<T>(o: T): (keyof T)[] {
    return Object.keys(o) as (keyof T)[];
  }

Access translations with:

import { translate } from './translate';
translate("Category.Home");

For further customization, consider storing the translation object in a separate file or implementing functionality for changing languages dynamically.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Iterating through an array and displaying information according to the quantity in node.js

Hey everyone, I have a simple task at hand where I am working with the following array: {items:[{upc:a,quantity:2},{upc:b,quantity:3}]} My goal is to transform it into the format shown below: {products:[{barcode:a},{barcode:a},{barcode:b},{barcode:b},{bar ...

Using JavaScript to add a JSON string from a POST request to an already existing JSON file

I am currently working on a basic express application that receives a post request containing JSON data. My goal is to take this data and add it to an existing JSON file, if one already exists. The key value pairs in the incoming JSON may differ from those ...

AngularJS version 1.5.11 experiencing issues with ng-repeat functionality

Having an application built on angularJS v1.5.11, I encountered a major issue while attempting to use ng-repeat in a table format like below: <tbody> <tr ng-repeat="score in data.result"> <td ng-repeat="item in score"> {{ item }} & ...

ghostly indentation post resizing

Can you please explain the mysterious appearance of ghostly indents upon clicking when the height is set to 0? These indents only become visible after the dropdown opens and the height is subsequently adjusted to zero. Also, what causes the jerky animation ...

Variation in Map Behavior in d3 Due to Datum-Data Discrepancy

I'm relatively new to utilizing d3js and I am endeavoring to grasp the distinction between employing data and datum for associating data with elements. Despite having spent quite some time reading various materials online, I still lack an instinctive ...

I'm looking for guidance on effectively utilizing filter and map within the reducers directory to manipulate the workouts objects

I am encountering an issue while trying to send delete and update requests for the workout object. The error message indicates that the filter function is not compatible as it's being applied to an object instead of an array. Here is the snippet of co ...

Activate the stripe button after successful bootstrap validation

My goal was to implement BootstrapValidator for validation on a couple of fields and enable the Stripe button only when both fields are valid. Currently, the button is enabled once any of the fields pass validation. The challenge lies in ensuring that the ...

Differences in Function Scope: A Comparison of ECMAScript 6 and ECMAScript 5

What are the advantages of ES6 compared to ES5 when it comes to block scope functions? Although the blocks may look similar in both cases, what impact does it have performance-wise and which approach is more efficient? ES6 Block { function fo ...

Typescript error: Cannot assign type 'undefined' to type 'string | number | symbol'

I need help figuring out how to address a TypeScript error in my code. Here's the scenario: export type status = 'success' | 'error' | undefined; There is an object that maps to different icons based on the status. const iconsMap: ...

Invoking Javascript Functions using their names

Suppose I have the following element on my page... <span data-function="DoSomething">Click</span> ... and then add the following to my page header... $(document).ready(function() { $('[data-function]').each(function() { ...

Exploring the differences between two string variables in JavaScript

While attempting to compare two strings using JavaScript, I encountered the following code: var statuss = document.getElementById("status").innerHTML; //alert(statuss); var s =statuss.toString(); var ss= "Active"; if (s === "Active"){ aler ...

AngularJS: Tips for bypassing filtering when inputting values outside of the range [1,2,3,4]

Is there a way to prevent filtering when entering certain numbers in the text box, like 0 or 5? <div ng-app=""> <input type="text" ng-model="search"> <div ng-repeat='val in [1,2, 3, 4] | filter:search'> {{val}} </div> ...

What method can be used to incorporate expressions into Handlebars partials when dealing with parameters?

Is it possible to include expressions in partials parameters? I am trying to achieve something similar to this: {{> myPartial greeting=(i18n.greeting + "my text") }} ...

Prevent repetitive content on your Node.js server

After realizing my small image hosting has many duplicate content, I am looking for a solution to prevent this issue in the future. My idea is to use either checksum or hash code so that whenever a new file is uploaded, it will be hashed and compared with ...

The subpage is not compatible with react-router 4

I've configured my router in the following way: <Switch> <PrivatePage key={index} {...opts} component={(props) => <Section {...props} pages={childRoutes} /> } /> <PrivatePage path='/accounts/:id' exact={t ...

Attempting to output properties from an Express/Mongo API by utilizing a React.js frontend

I am currently in the process of developing a simplistic fictional sneaker application with the MERN stack. While I wouldn't classify myself as a beginner, I'm also not an expert. I successfully created the backend and generated a json rest-api. ...

Ways to modify the HTML content within a span tag

I have a form in HTML that includes a span element whose content I want to change: <form action="javascript:submit()" id="form" class="panel_frame"> <label>Origin:</label> <div class="input-group" id="input-group"> ...

Leveraging the power of `.vue` files in modern web browsers that have native support for

Chrome 60 and the most recent version of Firefox, when used with certain flags enabled, have implemented support for import/export directives. I am interested in utilizing .vue files without relying on NodeJS, but I haven't been able to figure out how ...

How can I retrieve the text from two DIV elements simultaneously using JS/jQuery?

Is there a way to loop through all <TD> elements in order to store the Title and Link from each element into separate variables using JavaScript / jQuery? Sample HTML: <td> <div class="class_Title row border-bottom" name="name_Title" i ...

Is there an easy method for customizing scrollbars?

I'm looking to include an "overflow:scroll" in a navigation div, but the default scrollbar on windows is unattractive. Is there a simple way to customize the scrollbar without having to download extra JavaScript libraries, APIs, and so on? ...