Sync I18next JSON files with just ONE Comand

Michael Chan
2 min readFeb 26, 2020

Given my recent experience of developing a large scale React project, I’ve found that there are rarely exmaples of how to implement continuous localization easily for using the i18next file structure. If you are using the same/similar i18next file structure like my project as follows, you’re lucky…

/src
/locales
/data <-- (Putting into this folder is optional, just my case)
/en
dashboard.json
product.json
/zh-HK
dashboard.json
product.json

Let’s say the /en/dashboard.json is like this:

{ 
"title": "Dashboard",
"description": "Your dashboard of products."
}

And the /zh-HK/dashboard.json is like this:

{ 
"title": "儀表版",
"description": "你的產品儀表版"
}

Now say I want to add an "remark" text in the dashboard.json . In normal way you have to copy-and-paste that key to eachdasboard.json of every locale (in this case, /en and zh-HK ). It is still OK when you have only two language folders. But what if you have more then ten languages or you just missed one file and you didn’t know?

To streamline that process, I created a script to synchronize all JSON files of every locale, which would most likely just require you to type one command node syncI18nJSONs.js, after you have added some changes to one language. What it actually does is simply copy the JSON files of the base language, in my case en , to the JSON files of other languages without overwriting existing translation text (if there is any bug please tell me:).

Source

You can download the script here: https://gist.github.com/michchan/d3bb3a3f6c7a66c8971305713503ef5d

NOTE that you might need to change the following:

  • Change folder path: You have to change the folder path according to your project on the line: const LOCALES_PATH = 'src/locales/data' . The default value 'src/locales/data’ is just my case. You can also put it say outside of the src folder like 'public/locales'. The reason I don’t make it an argument is because you nearly won’t need to modify it once defined.
  • Change base language: You can also change the locale name of the base language on the line: const BASED_LNG = 'en' .

Usage Example

  1. Say my /en/dashboard.json now become like this:
{ 
"title": "Dashboard",
"description": "Your dashboard of products.",
"remark": "Note that these data are updated hourly."
}

2. Now I want the /zh-HK/dashboard.json to have the same structure. I just need to run node syncI18nJSON.js .

3. DONE! Now the /zh-HK/dashboard.json should become like:

{ 
"title": "儀表版",
"description": "你的產品儀表版",
"remark": ""
}

There are also some advanced usage but since they are not quite common so I won’t cover them here. I would be pleased if anyone feels this is useful. Feel free to raise if there is any question/issue.

--

--

Michael Chan

Based in Hong Kong, a passionate learner and perfectionist, who wants to build something cool with quality.