DEV Community

Bruno
Bruno

Posted on

How to work with nested locale folder structures in Vue

Recently, I was working on a Vue-based application where I decided to explore a bit how I could adapt the frontend architecture (or more specifically - the folder structure and the config, in this case) to work with multiple locale/translation files, including nested in other directories.

app folder structure for locales

Getting a single locale JSON file for each language is easy, especially if you work with Vite in your project, but what about multiple files for the same locale/language? Well, it is not that much of a big deal. I played around a bit with different solutions and our beloved ChatGPT has suggested the following approach.

The code

First step is to assign the translation files to a messages variable, and the catch here is, that if you want to assign a name to a specific set of translations (like "notifications", in this case), then you can just give it a key and assign the file to it:

import de from "./locale/de.json";
import en from "./locale/en.json";
import notificationsDe from "./locale/notifications/notifications_de.json";
import notificationsEn from "./locale/notifications/notifications_en.json";

// the rest of the code for the config bla bla...

const messages = {
  de: {
    ...de,
    notifications: notificationsDe,
  },
  en: {
    ...en,
    notifications: notificationsEn,
  },
};
Enter fullscreen mode Exit fullscreen mode

And then in your Vue files, you just use either the normal keys in the "main" translation files in the root of the locales directory, or access the notifications translations specifically:

<p>{{ $t('app.notifications-banner') }}</p>
<p>{{ $t('notifications.newMessage') }}</p>
Enter fullscreen mode Exit fullscreen mode

And then it will pick each translation accordingly.

Do I like this approach?

Yeah, sure. Why not? I mean, it works. Do I find it to be the cleanest, most efficient one? I am not sure. If I would write this from scratch for some other project right now, I would probably move the messages variable to a separate "utility" file instead, at least, just to keep the config file a bit cleaner and the locale stuff a bit more centralised. But as for an alternative solution, that is what I leave that up for discussion. I am curious if anyone has tried any other solutions than this, and if there is something better I have not thought of. 😉

Top comments (0)