reactjsinternationalizationreact-intl

react-intl shows warning when using defaultRichTextElements after compiling messages


I have a project created with create-react-app with typescript. I have been struggling with the best way to organize my messages. This is my approach:

{
  "a.hello": "<bold>hello</bold>",
  "a.world": "world",
  "another.another": "another <bold>message</bold>"
}

messages.ts

import { defineMessages } from "react-intl";

export default defineMessages({
  hello: {
    id: "a.hello",
    defaultMessage: "<bold>hello</bold>",
  },
  world: {
    id: "a.world",
    defaultMessage: "world",
  },
});

index.tsx

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import { IntlProvider } from "react-intl";
import enMessages from "./messages/en.json";

interface Props {
  children?: React.ReactNode;
}

const Bold = (props: Props) => {
  return (
    <div>
      <strong>{props.children}</strong>
    </div>
  );
};

ReactDOM.render(
  <IntlProvider
    locale="en"
    defaultLocale="en"
    messages={enMessages}
    defaultRichTextElements={{
      bold: (chunks) => <Bold>{chunks}</Bold>,
    }}
  >
    <App />
  </IntlProvider>,
  document.getElementById("root")
);

App.tsx

import "./App.css";
import messages from "./messages";
import { FormattedMessage } from "react-intl";

function App() {
  return (
    <div className="App">
      <FormattedMessage {...messages.hello} />{" "}
      <FormattedMessage {...messages.world} />
    </div>
  );
}

export default App;

I am extracting and compiling messages with this npm script:

"extract-compile": "formatjs extract 'src/**/*.ts*' --ignore='**/*.d.ts' --out-file temp.json --flatten --id-interpolation-pattern '[sha512:contenthash:base64:6]' && formatjs compile 'temp.json' --out-file src/messages/en.json && rm temp.json"

The problem is that I still getting this warning in console:

message.js:50 [@formatjs/intl] "defaultRichTextElements" was specified but "message" was not pre-compiled. 
Please consider using "@formatjs/cli" to pre-compile your messages for performance.
For more details see https://formatjs.io/docs/getting-started/message-distribution

Is there anything wrong with my approach? I think the warning should disappear, but I am missing something, obviously.


Solution

  • After digging in the documentation, it seems the flag --ast (not present in documentation example, but described in CLI doc) is the key.

    "extract-compile": "formatjs extract 'src/**/*.ts*' --ignore='**/*.d.ts' --out-file temp.json --flatten --id-interpolation-pattern '[sha512:contenthash:base64:6]' && formatjs compile 'temp.json'  --ast --out-file lang/en.json && rm temp.json",