iTranslated by AI
Implementing an i18next PostProcessor to Improve UI Visibility of Translated Text
When implementing internationalization (i18n), I wanted to make it easier to see on the screen which parts had already been processed for multi-language support.
Creating a PostProcessor
In the case of i18next, there is a plugin system, and this requirement could be handled by a PostProcessor.
The Processor itself was simple enough to be implemented as follows.
import i18n, { PostProcessorModule, TOptions } from "i18next"
const markingProcessor: PostProcessorModule = {
type: 'postProcessor',
name: 'marking',
process: (value: string, _key: string, _options: TOptions, _translator: any) => {
/* Display "Hello" as "[Hello]" */
return `[${value}]`
}
}
By doing this, the translated result will be displayed like [Hello], making it a plugin that helps you proceed with your work while checking the UI.
Using the PostProcessor
You can use it by specifying it with use during initialization and setting it as postProcess.
i18n
.use(markingProcessor)
.init({
// ...
postProcess: ["marking"]
// ...
})
In practice, it should only be used during development, so it is better to handle it by checking process.env.NODE_ENV or similar.
.init({
// ...
postProcess: process.env.NODE_ENV === "development" ? ["marking"] : []
// ...
})
A Little More Advanced
For example, if you want to display the key name as well, it would look something like this:
const markingProcessor: PostProcessorModule = {
type: 'postProcessor',
name: 'marking',
process: (value: string, key: string, _options: TOptions, translator: any) => {
// const resolved = translator.t(key)
/* return manipulated value */
return `[${key}:${value}]`
}
}
You could also do something like this to change the mark based on whether the key exists:
const markingProcessor: PostProcessorModule = {
type: 'postProcessor',
name: 'marking',
process: (value: string, key: string, _options: TOptions, translator: any) => {
const exist = translator.exists(key) ? "✅" : "❌"
return `${exist}:${value}`
}
}
By the way, translator is similar to typeof i18n but has slight discrepancies, and is currently defined as any in the official type definitions. If you want to know the exact details, looking at Translator.js is currently the most accurate way.
Discussion