HoverBaum

Ein Baum und seine Abenteuer

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:

1
2
βœ– 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.

1
2
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
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 πŸ§™β€

1
2
3
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.

⬅️ Go back