Browser SDK
Browser applications typically fetch a target-specific datafile and initialize the JavaScript SDK with application context.
Install#
Command
$ npm install @messagevisor/sdkBasic example#
Browser
import { createMessagevisor } from "@messagevisor/sdk";const response = await fetch("/datafiles/messagevisor-web-en-US.json");const datafile = await response.json();const m = createMessagevisor({ datafile, locale: "en-US", context: { platform: "web" },});console.log(m.translate("auth.signin"));Loading datafiles on demand#
For multi-locale apps, fetch the right datafile when the user switches locale and call setDatafile() and setLocale():
Browser
async function switchLocale(m, newLocale) { const response = await fetch(`/datafiles/messagevisor-web-${newLocale}.json`); const datafile = await response.json(); m.setDatafile(datafile); m.setLocale(newLocale);}Reading direction from the datafile#
After loading the datafile, the SDK can tell you the locale direction:
Browser
const direction = m.getDirection();document.documentElement.setAttribute("dir", direction);Why target-specific datafiles help#
Building a separate datafile per target (e.g. web, mobile) helps browser apps by:
- reducing download size - only the messages used by that surface are included
- reducing memory footprint
- eliminating irrelevant overrides and segments at build time rather than runtime
See Targets for how to configure message inclusion, locale lists, and format overrides per target.
Module setup for browser#
Modules must be registered before evaluation:
Browser
import { createMessagevisor } from "@messagevisor/sdk";import { createICUModule } from "@messagevisor/module-icu";const m = createMessagevisor({ datafile, locale: "en-US", modules: [createICUModule()],});
