ttag-org / ttag

:orange_book: simple approach for javascript localization
https://ttag.js.org/
MIT License
345 stars 43 forks source link

Translate constant #158

Closed ahrberg closed 5 years ago

ahrberg commented 5 years ago

Just trying out ttag and it's a really nice package and way of working with translations in the code. But I don't get constants to translate. Is this not supported or do I do something wrong?

const phrase = t`Hello`
const view = () => phrase
// `view ` returns a not translated string

Example: https://jsfiddle.net/7x385awv/1

Thanks!

ahrberg commented 5 years ago

Sorry, my bad. The variable was "translated" to default language. Need to reassign or similar after change of language.

Working example: https://jsfiddle.net/xzkLnjdm/

AlexMost commented 5 years ago

Hi @ahrberg! The problem could be also when the locale setup happens after constant import. The solution to this problem is to ensure that your locale setup happens before other imports. You can see an example here - https://github.com/ttag-org/CRA-runtime-example/blob/master/app/src/index.js#L1

The first import in the entry point:

import './i18nInit';

Glad that you have found our tool helpful! Feel free to ask any questions.

ahrberg commented 5 years ago

Thanks for you answer! I ended up with dynamic imports to have code splitting of the language files with Create React App. I will evaluate if this works out well.

index.tsx

(async () => {
  await setLocalization();
  const App = await import("./App");
  ReactDOM.render(<App.default />, document.getElementById("root"));
})();

i18init.ts

export const setLocalization = async (): Promise<void> => {
  const urlParams = new URLSearchParams(window.location.search);
  const locale = urlParams.get("hl");

  if (locale && locale !== "en") {
    const ret = await import(`./__generated__/${locale}.json`);
    addLocale(locale, ret.default);
    useLocale(locale);
  }
};