I created a custom Lingui wrapper in a React project:
function translate(translateObject: ITrenslatable) {
const { i18n, id, fallback, values, comment } = translateObject;
let translatedText = i18n._({
id,
message: fallback,
values,
comment,
});
if (translatedText == id) {
translatedText = i18n._({
id: Math.random().toString(),
message: fallback,
values,
comment,
});
}
return translatedText;
}
In the future, this custom wrapper may how additional features, and I'm also planning on making a <Translate /> tag that uses the function above under the hood to achieve custom translating behavior.
Edit: currently I need this function because:
- I want to create a layer of abstraction between my application and translation.
- I need this wrapper function to be able to provide a default
value, because otherwise if there were missing translations (e.g.
translation only available in English, and not Hungarian, only the
idwould be displayed when switched to Hungarian).
The custom function works exactly as expected when used on already extracted text, but unfortunately, I cannot extract from this function.
It looks like this when used:
translate({
i18n,
fallback: "User at {id}",
id: "user.title",
values: { id: props.id },
})
How do I make Lingui find and extract my custom translate function?
Thank you for reading!
I have not used Lingui myself and did no try out this solution, but according to the documentation, what you should probably do is:
Create a custom extractor that parses your code and inserts
/*i18n*/annotations to the calls of yourtranslatefunction, so the parameters passed to this function can then be picked up by the default extractor:...and add your extractor to the
lingui.config.tsfile:Please be aware that this is prone to some errors, e.g. if somebody choses to define an alias for the
translatefunction like this, the extraction will not work: