Val's Homepage

Illustration for Solving Translation Issues in Nuxt.js After Updating @nuxtjs/i18n

Solving Translation Issues in Nuxt.js After Updating @nuxtjs/i18n


Introduction

With the update of the @nuxtjs/i18n package from version 9.1.1 to 9.1.2 and beyond, I have encountered new challenges in handling translations. This article explores one such issue related to the langDir parameter and how it was circumvented.

Problem Description

Following the update to version 9.1.2 and above, the use of the $t function for translating keys started to throw errors. When changing languages within the application, keys that were previously translated correctly now resulted in errors like index.vue:6 [intlify] Not found 'home.p1' key in 'ja' locale messages.

Analysis

Upon investigation, it became clear that the issue was linked to the langDir parameter, which is responsible for loading translations from a specified directory. After the update, the system could no longer load translations from external JSON files properly, despite the correct setup of langDir in nuxt.config.ts.

Solution

The solution was unexpected but effective. Instead of loading translations from separate JSON files in the directory specified by langDir, the translations were moved directly into the i18n configuration file, i18n.config.ts.

In i18n.config.ts, all necessary translations for English and Japanese were added, structured within objects:

export default defineI18nConfig(() => ({
  legacy: false,
  locale: 'en',
  messages: {
    en: {
      welcome: 'Welcome',
      home: {
        p1: 'Hello!',
      },
      // ... other translations ...
    },
    ja: {
      welcome: 'ようこそ',
      home: {
        p1: 'こんにちは!',
      },
      // ... other translations ...
    },
  },
}));

In nuxt.config.ts, the langDir configuration was removed along with the file fields for each language, since translations are no longer loaded from external files:

i18n: {
  locales: [
    { code: 'en', iso: 'en-US' },
    { code: 'ja', iso: 'ja-JP' },
  ],
  defaultLocale: 'en',
}

Conclusion

Although the exact reason why changes to langDir stopped working remains unclear, this solution allows for continued internationalization support in Nuxt.js applications. Future updates to @nuxtjs/i18n might resolve this issue, but for now, moving translations into the configuration file serves as a reliable workaround.