32.0.0 • Published 2 months ago

tachyon-intl-server v32.0.0

Weekly downloads
-
License
UNLICENSED
Repository
-
Last release
2 months ago

Tachyon-Intl-Server

A SSR capable locale data provider for tachyon-intl.

  • consumes messages generated via twitch-intl-cli
  • capable of consuming localized application dependencies
  • intelligent locale loading to minimize bundle impact
  • locale fallback support to en-US
  • loads Twitch Custom CLDR package rules per locale to enable formatNumberShort
  • loads and provided Locale Data Hydration scripts to be executed on the client to Tachyon-Intl

Installation

$ yarn add tachyon-intl-server tachyon-intl

Integrating Into Your App

First, follow the setup guide for `tachyon-intl.

Then, install a prepareIntlDataCache call as part of server initialization. If your application relies on packages that have their own localization, list them through the includePackages option:

import { prepareIntlDataCache } from 'tachyon-intl-server';

// Load the data into a cache so that `selectIntlData` can read from it.
// Execute this only once per server instance at initialization
prepareIntlDataCache({
  includePackages: ['package-with-i18n'],
}).then(() => {
  // set up your server
  ...
});

In your application code, select a locale based on the user's preferences, and initialize the intl root:

import { selectIntlData } from 'tachyon-intl-server';
import { IntlData, TachyonIntlRoot } from 'tachyon-intl';
import { isBrowser } from 'tachyon-utils';

// Isomorphic function for getting the selected
function getSelectedIntlData(): ClientIntlData {
  // readAcceptLanguageHeader is a function you'll need to implement to read the
  // 'Accept-Language' header on the server.
  const userAcceptLanguages: string[] = readAcceptLanguageHeader();

  let selectedIntlData: IntlData;
  if (!isBrowser()) {
    // After intl data is selected, make sure it gets serialized and sent to the client.
    selectedIntlData = selectIntlData(userAcceptLanguages);
  } else {
    // read the selected bundle using the server -> client serialization method your
    // app utilizes
  }

  return selectedIntlData;
}

export function renderApp(): JSX.Element {
  // Selects a locale from the using best fit given user preferences
  // based on those your application supports
  const selectedIntlData = getSelectedIntlData();

  return (
    <html>
      <div>
        <TachyonIntlRoot data={selectedIntlData}>
          {/* App JSX */}
        </TachyonIntlRoot>
      </div>
    </html>
  );
}

Testing

The messages directory in this package is merely a mock for testing message loading functionality.