1

I'm implementing a localized react app using react-intl. I have a folder with all translations. I want to dynamically import all the translations and also get the filenames to display a dropdown with available languages on the page.

Currently I have to hardcode each language:

import {IntlProvider, FormattedMessage} from 'react-intl'

import messages_de from '../translations/de.json'
import messages_en from '../translations/en.json'

const messages = {
 'de': messages_de,
 'en': messages_en,
};

const i18nConfig = {
 defaultLocale: 'en',
 messages,
};

Is there a way to get a list of files (e.g. before compiling an app) which I can then access within react components?

Aray Karjauv
  • 2,679
  • 2
  • 26
  • 44

1 Answers1

1

I ended up with the following solution:

// search for .json files
const webpackContext = require.context('../translations', false, /\.json$/)

const filenames = webpackContext.keys() // => ['./de.json, './en.json']

const key_value_pairs = filenames.map(name => [name.match(/\/(\w+)\.json$/)[1], webpackContext(name)])

// make a dictionary from the array of arrays
const messages = Object.fromEntries(key_value_pairs)

This code imports dynamically all files into a dictionary where the key is the filename.

require.context takes a directory to search, a flag indicating whether subdirectories should be searched too, and a regular expression to match files against.

The returned function webpackContext is the most confusing part. Although it is a function, it also has properties, because everything is an object in js. webpackContext.keys() returns a list of filenames in given directory matching given regex.

Finally, webpackContext(name) imports a file.

The code above is equivalent to the following code:

import messages_de from '../translations/de.json'
import messages_en from '../translations/en.json'

const messages = {
 'de': messages_de,
 'en': messages_en,
};
Aray Karjauv
  • 2,679
  • 2
  • 26
  • 44
  • help me understanding how `webpackContext(name)` imports a file – miraj Feb 15 '21 at 05:22
  • It imports a file with the name `name` like js `import` statement . In my case, it loads `json` for each language. I map language name and its json – Aray Karjauv Feb 15 '21 at 12:29