Skip to main content

Installation

formatjs is a set of libraries that help you setup internationalization in any project whether it's React or not.

Installation

npm i -S react react-intl

Minimal Application

After following the step above, you should be able to get a minimal application like this running:

import * as React from 'react'
import {IntlProvider, FormattedMessage, FormattedNumber} from 'react-intl'

// Translated messages in French with matching IDs to what you declared
const messagesInFrench = {
myMessage: "Aujourd'hui, nous sommes le {ts, date, ::yyyyMMdd}",
}

export default function App() {
return (
<IntlProvider messages={messagesInFrench} locale="fr" defaultLocale="en">
<p>
<FormattedMessage
id="myMessage"
defaultMessage="Today is {ts, date, ::yyyyMMdd}"
values={{ts: Date.now()}}
/>
<br />
<FormattedNumber value={19} style="currency" currency="EUR" />
</p>
</IntlProvider>
)
}

Output

<p>
Aujourd'hui, nous sommes le 23/07/2020
<br />
19,00 €
</p>

Adding our babel-plugin/TypeScript Transformer for compilation

Our tooling supports babel, ts-loader, ts-jest, rollup-plugin-typescript2 & ts-patch for message compilation:

Babel

If you're using babel, add babel-plugin-formatjs to your dependencies:

npm i -D babel-plugin-formatjs

and add it to your babel.config.js or .babelrc:

{
"plugins": [
[
"formatjs",
{
"idInterpolationPattern": "[sha512:contenthash:base64:6]",
"ast": true
}
]
]
}

ts-loader

npm i -D @formatjs/ts-transformer
import {transform} from '@formatjs/ts-transformer'

module.exports = {
...otherConfigs,
module: {
rules: [
{
test: /\.tsx?$/,
use: [
{
loader: 'ts-loader',
options: {
getCustomTransformers() {
return {
before: [
transform({
overrideIdFn: '[sha512:contenthash:base64:6]',
}),
],
}
},
},
},
],
},
],
},
}

ts-jest in jest.config.js

npm i -D @formatjs/ts-transformer

Take a look at ts-jest guide on how to incorporate custom AST Transformers.

ts-patch

npm i -D @formatjs/ts-transformer
{
"compilerOptions": {
"plugins": [
{
"transform": "@formatjs/ts-transformer",
"import": "transform",
"type": "config",
"overrideIdFn": "[sha512:contenthash:base64:6]",
"ast": true
}
]
}
}

rollup-plugin-typescript2

npm i -D @formatjs/ts-transformer
// rollup.config.js
import typescript from 'rollup-plugin-typescript2'
import {transform} from '@formatjs/ts-transformer'

export default {
input: './main.ts',

plugins: [
typescript({
transformers: () => ({
before: [
transform({
overrideIdFn: '[sha512:contenthash:base64:6]',
ast: true,
}),
],
}),
}),
],
}