fnando / i18n-js

It's a small library to provide the I18n translations on the Javascript. It comes with Rails support.
MIT License
3.77k stars 520 forks source link

Feature Request: Add ability to export JS files #662

Closed TheTrio closed 1 year ago

TheTrio commented 2 years ago

According to the migration guide, export_i18n_js has been removed without an equivalent.

I tried fetching the generated JSON files via fetch but the problem is that since that is non blocking, other scripts which rely on the global I18n error out.

This is how things work right now

In my haml file, I do

:javascript
    locale = "#{I18n.locale.to_s}"

And then I access this global from my main script to fetch the json files.

async function loadTranslations(i18n, locale) {
  const response = await fetch(`/assets/javascripts/i18n/${locale}.json`);
  const translations = await response.json();
  i18n.store(translations);
}

But while this waits on the main script, it sends control to other scripts, which rely on I18n.

My workaround for this right now is reading the file via Ruby and injecting it in the javascript. Something like this.

:javascript
    locale_json = #{File.read("public/assets/javascripts/i18n/#{I18n.locale.to_s}.js").html_safe}

I'm not sure if this has any performances penalties but it does look kind of ugly. Is there a better way to do this? Having the ability to export JS files would solve this issue but I assume there's a good way to do it without it.

TheTrio commented 1 year ago

Thanks! This works perfectly!