Extending messages hook

Nuxt hooks to extend i18n messages in your project.


If you're a module author and want that module to provide extra messages for your project, you can merge them into the normally loaded messages by using the i18n:registerModule hook.

This is particularly useful if your module uses translated content and you want to offer nice default translations.

In your module's setup file listen to the Nuxt i18n:registerModule hook and register your i18n configuration, this is similar to how lazy-load translations are configured.

Translations added this way will be loaded after those added in your project, and before extended layers.

Example:

my-module-example/module.ts
import { createResolver, defineNuxtModule } from '@nuxt/kit'

export default defineNuxtModule({
  async setup(options, nuxt) {
    const { resolve } = createResolver(import.meta.url)

    nuxt.hook('i18n:registerModule', register => {
      register({
        // langDir path needs to be resolved
        langDir: resolve('./lang'),
        locales: [
          {
            code: 'en',
            file: 'en.json',
          },
          {
            code: 'fr',
            file: 'fr.json',
          },
        ]
      })
    })
  }
})
{
  "my-module-example": {
    "hello": "Hello from external module"
  }
}
{
  "my-module-example": {
    "hello": "Bonjour depuis le module externe"
  }
}

Now the project has access to new messages and can use them through $t('my-module-example.hello').

These hooks will only work for modules registered before the @nuxtjs/i18n module.
nuxt.config.ts
import ExampleModule from './my-module-example/module.ts' // import your custom module

export default defineNuxtConfig({
  modules: [
    ExampleModule,
    '@nuxtjs/i18n',
  ],
})
Because module's messages are merged with the project's ones, it's safer to prefix them. Main project messages will always override messages provided by modules.