Contentful import to a different locale
After my recent undertaking to migrate a blog from Wordpress to Contentful I was also faced with the challenge to import content to a Space that had a different locale than the Space it was exported from. This came about after we setup a "base" space for our Product that is supposed to be rolled out in multiple countries.
Once again I wanted to use the Contentful-import tool to get this job done. However soon I kept seeing:
✖ Checking if destination space already has any content and retrieving it
→ Default locale for destination space: es-ES
And while Contentful-bootstrap supports a --locale
flag to do this it is a now unsupported Ruby based tool. As a webdeveloper I obviously want to use a Node based tool like Contentful-import.
It the solution is quite easy, we simply need to replace each occurrence of the tarting locale with the desired one. Using a regular expression on the JSON representation of our exported space makes this a breeze.
const desiredLocale = 'es-ES'
const replacesLocaleCodes = space.replace(/en-US/g, desiredLocale)
Super simple really. After running our exported Space through this we can run our import with it and succeed 🎉
Gotchas
However we will now find that our Space has a default locale called "English" that is the Spanish language 😕
To change that we need to replace the locale object in the .locale
attribute of our exported space with the correct one for our target space. Assuming we have an array of locales exported from Contentful we can achieve this quite easily.
const targetLocale = 'es-ES'
// Assuming array locales with locale objects exported from Contentful.
if (!locales.find((locale) => locale.code === targetLocale)) {
console.log(`Sorry, but we don't support ${targetLocale}`)
}
// Again assuming you have a way to get your space.
const space = await getExportedSpace()
const replacesLocaleCodes = space.replace(/en-US/g, targetLocale)
const parsedSpace = JSON.parse(replacesLocaleCodes)
parsedSpace.locales = [locales.find((locale) => locale.code === targetLocale)]
console.log(JSON.stringify(parsedSpace, null, 2))
Creating a util
Because this is bothersome and I am probably not the only one facing this problem you can find my solution on Github and install it via npm 🧙
npm install -g @hoverbaum/contentful-locale
contentful-locale exportedSpace.json target-locale -s output.json
You can also find the original code as a Gist.