⚡ High Performance
🚀 Significant reductions in build times, memory usage, and server load, making it ideal for large-scale projects.
diff --git a/.nojekyll b/.nojekyll new file mode 100644 index 00000000..e69de29b diff --git a/1.65.0.jpg b/1.65.0.jpg new file mode 100644 index 00000000..e9bd9f4f Binary files /dev/null and b/1.65.0.jpg differ diff --git a/404.html b/404.html new file mode 100644 index 00000000..f73591cb --- /dev/null +++ b/404.html @@ -0,0 +1,22 @@ + + +
+ + +i18n:register
The i18n:register
event in Nuxt I18n Micro
enables dynamic addition of translations to your application's global i18n context, making the internationalization process seamless and flexible. This event allows you to integrate new translations as needed, enhancing your application's localization capabilities.
Purpose:
Payload:
register
: translations
(Translations
): Translations
interface.locale
(string
, optional): 'en'
, 'ru'
) for which the translations are registered. Defaults to the locale provided by the event if not specified.Behavior:
register
function merges the new translations into the global context for the specified locale, updating the available translations across the application.The following example demonstrates how to use the i18n:register
event to dynamically add translations:
nuxt.hook('i18n:register', async (register: (translations: unknown, locale?: string) => void, locale: string) => {
+ register({
+ "greeting": "Hello",
+ "farewell": "Goodbye"
+ }, locale);
+});
Triggering the Event:
i18n:register
lifecycle event provided by Nuxt I18n Micro
.Adding Translations:
"greeting"
and "farewell"
.register
function merges these translations into the existing set for the provided locale.Dynamic Updates:
Localization Flexibility:
Using the i18n:register
event, you can ensure that your application's localization strategy remains flexible and adaptable, enhancing the overall user experience.
To modify translations dynamically in your Nuxt application, using plugins is recommended. Plugins provide a structured way to handle localization updates, especially when working with modules or external translation files.
If you're using a module, register the plugin where translation modifications will occur by adding it to your module’s configuration:
addPlugin({
+ src: resolve('./plugins/extend_locales'),
+})
This registers the plugin located at ./plugins/extend_locales
, which will handle dynamic loading and registration of translations.
In the plugin, you can manage locale modifications. Here's an example implementation in a Nuxt plugin:
import { defineNuxtPlugin } from '#app'
+
+export default defineNuxtPlugin(async (nuxtApp) => {
+ // Function to load translations from JSON files and register them
+ const loadTranslations = async (lang: string) => {
+ try {
+ const translations = await import(\`../locales/\${lang}.json\`)
+ return translations.default
+ } catch (error) {
+ console.error(\`Error loading translations for language: \${lang}\`, error)
+ return null
+ }
+ }
+
+ // Hook into the 'i18n:register' event to dynamically add translations
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
+ // @ts-expect-error
+ nuxtApp.hook('i18n:register', async (register: (translations: unknown, locale?: string) => void, locale: string) => {
+ const translations = await loadTranslations(locale)
+ if (translations) {
+ register(translations, locale)
+ }
+ })
+})
loadTranslations
function dynamically imports translation files based on the locale. The files are expected to be in the locales
directory and named according to locale codes (e.g., en.json
, de.json
).i18n:register
event using nuxtApp.hook
.register
function is called with the loaded translations and the corresponding locale.Separation of Concerns:
Dynamic and Scalable:
Enhanced Localization Flexibility:
By adopting this approach, you can efficiently expand and modify your application's localization through a structured and maintainable process using plugins, keeping internationalization adaptive to changing needs and improving the overall user experience.
`,31)]))}const c=s(e,[["render",l]]);export{g as __pageData,c as default}; diff --git a/assets/api_events.md.bHhRa_Pw.lean.js b/assets/api_events.md.bHhRa_Pw.lean.js new file mode 100644 index 00000000..08a72755 --- /dev/null +++ b/assets/api_events.md.bHhRa_Pw.lean.js @@ -0,0 +1,31 @@ +import{_ as s,c as a,a2 as n,o as t}from"./chunks/framework.Gfs4HC1t.js";const g=JSON.parse('{"title":"📢 Events","description":"","frontmatter":{"outline":"deep"},"headers":[],"relativePath":"api/events.md","filePath":"api/events.md","lastUpdated":1727601432000}'),e={name:"api/events.md"};function l(h,i,p,r,o,k){return t(),a("div",null,i[0]||(i[0]=[n(`i18n:register
The i18n:register
event in Nuxt I18n Micro
enables dynamic addition of translations to your application's global i18n context, making the internationalization process seamless and flexible. This event allows you to integrate new translations as needed, enhancing your application's localization capabilities.
Purpose:
Payload:
register
: translations
(Translations
): Translations
interface.locale
(string
, optional): 'en'
, 'ru'
) for which the translations are registered. Defaults to the locale provided by the event if not specified.Behavior:
register
function merges the new translations into the global context for the specified locale, updating the available translations across the application.The following example demonstrates how to use the i18n:register
event to dynamically add translations:
nuxt.hook('i18n:register', async (register: (translations: unknown, locale?: string) => void, locale: string) => {
+ register({
+ "greeting": "Hello",
+ "farewell": "Goodbye"
+ }, locale);
+});
Triggering the Event:
i18n:register
lifecycle event provided by Nuxt I18n Micro
.Adding Translations:
"greeting"
and "farewell"
.register
function merges these translations into the existing set for the provided locale.Dynamic Updates:
Localization Flexibility:
Using the i18n:register
event, you can ensure that your application's localization strategy remains flexible and adaptable, enhancing the overall user experience.
To modify translations dynamically in your Nuxt application, using plugins is recommended. Plugins provide a structured way to handle localization updates, especially when working with modules or external translation files.
If you're using a module, register the plugin where translation modifications will occur by adding it to your module’s configuration:
addPlugin({
+ src: resolve('./plugins/extend_locales'),
+})
This registers the plugin located at ./plugins/extend_locales
, which will handle dynamic loading and registration of translations.
In the plugin, you can manage locale modifications. Here's an example implementation in a Nuxt plugin:
import { defineNuxtPlugin } from '#app'
+
+export default defineNuxtPlugin(async (nuxtApp) => {
+ // Function to load translations from JSON files and register them
+ const loadTranslations = async (lang: string) => {
+ try {
+ const translations = await import(\`../locales/\${lang}.json\`)
+ return translations.default
+ } catch (error) {
+ console.error(\`Error loading translations for language: \${lang}\`, error)
+ return null
+ }
+ }
+
+ // Hook into the 'i18n:register' event to dynamically add translations
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
+ // @ts-expect-error
+ nuxtApp.hook('i18n:register', async (register: (translations: unknown, locale?: string) => void, locale: string) => {
+ const translations = await loadTranslations(locale)
+ if (translations) {
+ register(translations, locale)
+ }
+ })
+})
loadTranslations
function dynamically imports translation files based on the locale. The files are expected to be in the locales
directory and named according to locale codes (e.g., en.json
, de.json
).i18n:register
event using nuxtApp.hook
.register
function is called with the loaded translations and the corresponding locale.Separation of Concerns:
Dynamic and Scalable:
Enhanced Localization Flexibility:
By adopting this approach, you can efficiently expand and modify your application's localization through a structured and maintainable process using plugins, keeping internationalization adaptive to changing needs and improving the overall user experience.
`,31)]))}const c=s(e,[["render",l]]);export{g as __pageData,c as default}; diff --git a/assets/api_methods.md.VL5OYeZ9.js b/assets/api_methods.md.VL5OYeZ9.js new file mode 100644 index 00000000..7fb69d25 --- /dev/null +++ b/assets/api_methods.md.VL5OYeZ9.js @@ -0,0 +1,128 @@ +import{_ as i,c as a,a2 as t,o as n}from"./chunks/framework.Gfs4HC1t.js";const g=JSON.parse('{"title":"🛠️ Methods","description":"","frontmatter":{"outline":"deep"},"headers":[],"relativePath":"api/methods.md","filePath":"api/methods.md","lastUpdated":1736500399000}'),e={name:"api/methods.md"};function l(h,s,p,k,r,o){return n(),a("div",null,s[0]||(s[0]=[t(`$getLocale
() => string
const locale = $getLocale()
+// Output: 'en' (assuming the current locale is English)
$getLocaleName
Version introduced: v1.28.0
() => string | null
const locale = $getLocaleName()
+// Output: 'English'
$getLocales
() => Array<{ code: string; iso?: string; dir?: string }>
const locales = $getLocales()
+// Output: [{ code: 'en', iso: 'en-US', dir: 'ltr' }, { code: 'fr', iso: 'fr-FR', dir: 'ltr' }]
$getRouteName
Version introduced: v1.28.0
(route?: RouteLocationNormalizedLoaded | RouteLocationResolvedGeneric, locale?: string) => string
RouteLocationNormalizedLoaded | RouteLocationResolvedGeneric | undefined
— Optional. The route object from which to extract the name.string | undefined
— Optional. The locale code to consider when extracting the route name.const routeName = $getRouteName(routeObject, 'fr')
+// Output: 'index' (assuming the base route name is 'index')
$t
Type: (key: string, params?: Record<string, any>, defaultValue?: string) => string | number | boolean | Translations | PluralTranslations | unknown | null
Description: Fetches a translation for the given key. Optionally interpolates parameters.
Parameters:
string
— The translation key.Record<string, any> | undefined
— Optional. A record of key-value pairs to interpolate into the translation.string | undefined
— Optional. The default value to return if the translation is not found.Example:
const welcomeMessage = $t('welcome', { username: 'Alice', unreadCount: 5 })
+// Output: "Welcome, Alice! You have 5 unread messages."
$ts
(key: string, params?: Record<string, any>, defaultValue?: string) => string
$t
that always returns a string. Fetches a translation for the given key and optionally interpolates parameters.string
— The translation key.Record<string, any> | undefined
— Optional. A record of key-value pairs to interpolate into the translation.string | undefined
— Optional. The default value to return if the translation is not found.const welcomeMessage = $ts('welcome', { username: 'Alice', unreadCount: 5 })
+// Output: "Welcome, Alice! You have 5 unread messages."
$tc
(key: string, count: number, defaultValue?: string) => string
string
— The translation key.number | Record<string, any>
— The count for pluralization or a record of key-value pairs with a 'count' property and additional values to interpolate into the translation.string | undefined
— Optional. The default value to return if the translation is not found.const appleCountMessage = $tc('apples', 10)
+// Output: "10 apples" (assuming the plural rule for 'apples' is defined correctly)
$tn
(value: number, options?: Intl.NumberFormatOptions) => string
Intl.NumberFormat
.number
— The number to format.Intl.NumberFormatOptions | undefined
— Optional. Intl.NumberFormatOptions
to customize the formatting.const formattedNumber = $tn(1234567.89, { style: 'currency', currency: 'USD' })
+// Output: "$1,234,567.89" in the 'en-US' locale
Use Cases:
Intl.NumberFormatOptions
such as currency, minimum fraction digits, etc.$td
(value: Date | number | string, options?: Intl.DateTimeFormatOptions) => string
Intl.DateTimeFormat
.Date | number | string
— The date to format, which can be a Date
object, a timestamp, or a date string.Intl.DateTimeFormatOptions | undefined
— Optional. Intl.DateTimeFormatOptions
to customize the formatting.const formattedDate = $td(new Date(), { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })
+// Output: "Friday, September 1, 2023" in the 'en-US' locale
Use Cases:
$tn
(value: number | string, options?: Intl.NumberFormatOptions) => string
Intl.NumberFormat
.number | string
— The number to format, which can be a number
or a numeric string
.Intl.NumberFormatOptions | undefined
— Optional. Intl.NumberFormatOptions
to customize the number formatting.const formattedNumber = $tn(1234567.89, { style: 'currency', currency: 'USD' })
+// Output: "$1,234,567.89" in the 'en-US' locale
$tdr
(value: Date | number | string, options?: Intl.RelativeTimeFormatOptions) => string
Intl.RelativeTimeFormat
.Date | number | string
— The date to compare against the current time, which can be a Date
object, a timestamp, or a date string.Intl.RelativeTimeFormatOptions | undefined
— Optional. Intl.RelativeTimeFormatOptions
to customize the relative time formatting.const relativeDate = $tdr(new Date(Date.now() - 1000 * 60 * 5))
+// Output: "5 minutes ago" in the 'en-US' locale
$switchLocaleRoute
(locale: string) => RouteLocationRaw
string
— Target locale.// on /en/news
+const routeFr = $switchLocaleRoute('fr')
+// Output: A route object with the new locale applied, e.g., { name: 'localized-news', params: { locale: 'fr' } }
$switchLocalePath
(locale: string) => string
string
— Target locale.// on /en/news
+const routeFr = $switchLocalePath('fr')
+window.location.href = routeFr
+// Output: url with new locale applied, e.g., '/fr/nouvelles'
$switchLocale
(locale: string) => void
string
— The locale to switch to.$switchLocale('fr')
+// Output: Redirects the user to the French version of the route
$switchRoute
Version introduced: v1.27.0
(route: RouteLocationNormalizedLoaded | RouteLocationResolvedGeneric | string, toLocale?: string) => void
RouteLocationNormalizedLoaded | RouteLocationResolvedGeneric | string
— The route to which you want to switch. It can be: RouteLocationNormalizedLoaded
or RouteLocationResolvedGeneric
object.string
— The locale to switch to for the target route. If not provided, the current locale is used.Info: This method facilitates seamless switching between routes, accommodating the current locale configuration. Depending on the input, it resolves the intended route and determines the appropriate locale for redirecting the user to a localized route.
Examples:
String Path:
// Switches to the given path with the current locale
+switchRoute('/about')
String Path with Locale:
// Switches to the given path with French locale
+switchRoute('/about', 'fr')
Named Route:
// Switches to a named route with the current locale
+switchRoute({ name: 'page' })
Named Route with Locale:
// Switches to a named route and changes the locale to Spanish
+switchRoute({ name: 'page' }, 'es')
$setI18nRouteParams
(value: Record<LocaleCode, Record<string, string>> | null) => Record<LocaleCode, Record<string, string>> | null
Record<LocaleCode, Record<string, string>> | null
— params of current route for other locale// in pages/news/[id].vue
+// for en/news/1-first-article
+const { $switchLocaleRoute, $setI18nRouteParams, $defineI18nRoute } = useI18n();
+// OR
+const { $switchLocaleRoute, $setI18nRouteParams, $defineI18nRoute } = useNuxtApp();
+$defineI18nRoute({
+ localeRoutes: {
+ en: '/news/:id()',
+ fr: '/nouvelles/:id()',
+ de: '/Nachricht/:id()',
+ },
+})
+const { data: news } = await useAsyncData(\`news-\${params.id}\`, async () => {
+ let response = await $fetch("/api/getNews", {
+ query: {
+ id: params.id,
+ },
+ });
+ if (response?.localeSlugs) {
+ response.localeSlugs = {
+ en: {
+ id: '1-first-article'
+ }
+ fr: {
+ id: '1-premier-article'
+ }
+ de: {
+ id: '1-erster-Artikel'
+ }
+ }
+ $setI18nRouteParams(response?.localeSlugs);
+ }
+ return response;
+});
+$switchLocalePath('fr') // === 'fr/nouvelles/1-premier-article'
+$switchLocalePath('de') // === 'de/Nachricht/1-erster-Artikel'
$localeRoute
(to: RouteLocationRaw, locale?: string) => RouteLocationResolved
RouteLocationRaw
— The target route object.string | undefined
— Optional. The locale for the generated route.const localizedRoute = $localeRoute({ name: 'index' })
+// Output: A route object with the current locale applied, e.g., { name: 'index', params: { locale: 'fr' } }
$localePath
(to: RouteLocationRaw, locale?: string) => string
RouteLocationRaw
— The target route object.string | undefined
— Optional. The locale for the generated route.const localizedRoute = $localeRoute({ name: 'news' })
+// Output: url with new locale applied, e.g., '/en/nouvelles'
$mergeTranslations
(newTranslations: Record<string, string>) => void
Record<string, string>
— The new translations to merge.$mergeTranslations({
+ welcome: 'Bienvenue, {username}!'
+})
+// Output: Updates the translation cache with the new French translation
$defineI18nRoute
(routeDefinition: { locales?: string[] | Record<string, Record<string, TranslationObject>>, localeRoutes?: Record<string, string> }) => void
string[] | Record<string, Record<string, TranslationObject>>
— This property determines which locales are available for the route.Record<string, string> | undefined
— Optional. Custom routes for specific locales.$defineI18nRoute({
+ locales: {
+ en: { greeting: 'Hello', farewell: 'Goodbye' },
+ ru: { greeting: 'Привет', farewell: 'До свидания' },
+ },
+ localeRoutes: {
+ ru: '/localesubpage',
+ },
+})
Use Cases:
Controlling Access: By specifying available locales, you can control which routes are accessible based on the current locale, ensuring that users only see content relevant to their language.
Providing Translations: The locales
object allows for providing specific translations for each route, enhancing the user experience by delivering content in the user's preferred language.
Custom Routing: The localeRoutes
property offers flexibility in defining different paths for specific locales, which can be particularly useful in cases where certain languages or regions require unique navigational flows or URLs.
This function offers a flexible way to manage routing and localization in your Nuxt application, making it easy to tailor the user experience based on the language and region settings of your audience.
Example 1: Controlling Access Based on Locales
import { useNuxtApp } from '#imports'
+
+const { $defineI18nRoute } = useNuxtApp()
+
+$defineI18nRoute({
+ locales: ['en', 'fr', 'de'] // Only these locales are allowed for this route
+})
Example 2: Providing Translations for Locales
import { useNuxtApp } from '#imports'
+
+const { $defineI18nRoute } = useNuxtApp()
+
+$defineI18nRoute({
+ locales: {
+ en: { greeting: 'Hello', farewell: 'Goodbye' },
+ fr: { greeting: 'Bonjour', farewell: 'Au revoir' },
+ de: { greeting: 'Hallo', farewell: { aaa: { bbb: "Auf Wiedersehen" } } },
+ ru: {} // Russian locale is allowed but no translations are provided
+ }
+})
📝 Explanation:
{}
) for that locale.Here's an example of how to use these methods in a Nuxt component:
<template>
+ <div>
+ <p>{{ $t('key2.key2.key2.key2.key2') }}</p>
+ <p>Current Locale: {{ $getLocale() }}</p>
+
+ <div>
+ {{ $t('welcome', { username: 'Alice', unreadCount: 5 }) }}
+ </div>
+ <div>
+ {{ $tc('apples', 10) }}
+ </div>
+
+ <div>
+ <button
+ v-for="locale in $getLocales()"
+ :key="locale"
+ :disabled="locale === $getLocale()"
+ @click="() => $switchLocale(locale.code)"
+ >
+ Switch to {{ locale.code }}
+ </button>
+ </div>
+
+ <div>
+ <NuxtLink :to="$localeRoute({ name: 'index' })">
+ Go to Index
+ </NuxtLink>
+ </div>
+ </div>
+</template>
+
+<script setup>
+import { useI18n } from '#imports'
+
+const { $getLocale, $switchLocale, $getLocales, $localeRoute, $t, $tc } = useI18n()
+</script>
useNuxtApp
Example:
import { useNuxtApp } from '#imports'
+
+const { $getLocale, $switchLocale, $getLocales, $localeRoute, $t } = useNuxtApp()
useI18n
Composable Example:
import { useI18n } from '#imports'
+
+const { $getLocale, $switchLocale, $getLocales, $localeRoute, $t } = useI18n()
+// or
+const i18n = useI18n()
$getLocale
() => string
const locale = $getLocale()
+// Output: 'en' (assuming the current locale is English)
$getLocaleName
Version introduced: v1.28.0
() => string | null
const locale = $getLocaleName()
+// Output: 'English'
$getLocales
() => Array<{ code: string; iso?: string; dir?: string }>
const locales = $getLocales()
+// Output: [{ code: 'en', iso: 'en-US', dir: 'ltr' }, { code: 'fr', iso: 'fr-FR', dir: 'ltr' }]
$getRouteName
Version introduced: v1.28.0
(route?: RouteLocationNormalizedLoaded | RouteLocationResolvedGeneric, locale?: string) => string
RouteLocationNormalizedLoaded | RouteLocationResolvedGeneric | undefined
— Optional. The route object from which to extract the name.string | undefined
— Optional. The locale code to consider when extracting the route name.const routeName = $getRouteName(routeObject, 'fr')
+// Output: 'index' (assuming the base route name is 'index')
$t
Type: (key: string, params?: Record<string, any>, defaultValue?: string) => string | number | boolean | Translations | PluralTranslations | unknown | null
Description: Fetches a translation for the given key. Optionally interpolates parameters.
Parameters:
string
— The translation key.Record<string, any> | undefined
— Optional. A record of key-value pairs to interpolate into the translation.string | undefined
— Optional. The default value to return if the translation is not found.Example:
const welcomeMessage = $t('welcome', { username: 'Alice', unreadCount: 5 })
+// Output: "Welcome, Alice! You have 5 unread messages."
$ts
(key: string, params?: Record<string, any>, defaultValue?: string) => string
$t
that always returns a string. Fetches a translation for the given key and optionally interpolates parameters.string
— The translation key.Record<string, any> | undefined
— Optional. A record of key-value pairs to interpolate into the translation.string | undefined
— Optional. The default value to return if the translation is not found.const welcomeMessage = $ts('welcome', { username: 'Alice', unreadCount: 5 })
+// Output: "Welcome, Alice! You have 5 unread messages."
$tc
(key: string, count: number, defaultValue?: string) => string
string
— The translation key.number | Record<string, any>
— The count for pluralization or a record of key-value pairs with a 'count' property and additional values to interpolate into the translation.string | undefined
— Optional. The default value to return if the translation is not found.const appleCountMessage = $tc('apples', 10)
+// Output: "10 apples" (assuming the plural rule for 'apples' is defined correctly)
$tn
(value: number, options?: Intl.NumberFormatOptions) => string
Intl.NumberFormat
.number
— The number to format.Intl.NumberFormatOptions | undefined
— Optional. Intl.NumberFormatOptions
to customize the formatting.const formattedNumber = $tn(1234567.89, { style: 'currency', currency: 'USD' })
+// Output: "$1,234,567.89" in the 'en-US' locale
Use Cases:
Intl.NumberFormatOptions
such as currency, minimum fraction digits, etc.$td
(value: Date | number | string, options?: Intl.DateTimeFormatOptions) => string
Intl.DateTimeFormat
.Date | number | string
— The date to format, which can be a Date
object, a timestamp, or a date string.Intl.DateTimeFormatOptions | undefined
— Optional. Intl.DateTimeFormatOptions
to customize the formatting.const formattedDate = $td(new Date(), { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })
+// Output: "Friday, September 1, 2023" in the 'en-US' locale
Use Cases:
$tn
(value: number | string, options?: Intl.NumberFormatOptions) => string
Intl.NumberFormat
.number | string
— The number to format, which can be a number
or a numeric string
.Intl.NumberFormatOptions | undefined
— Optional. Intl.NumberFormatOptions
to customize the number formatting.const formattedNumber = $tn(1234567.89, { style: 'currency', currency: 'USD' })
+// Output: "$1,234,567.89" in the 'en-US' locale
$tdr
(value: Date | number | string, options?: Intl.RelativeTimeFormatOptions) => string
Intl.RelativeTimeFormat
.Date | number | string
— The date to compare against the current time, which can be a Date
object, a timestamp, or a date string.Intl.RelativeTimeFormatOptions | undefined
— Optional. Intl.RelativeTimeFormatOptions
to customize the relative time formatting.const relativeDate = $tdr(new Date(Date.now() - 1000 * 60 * 5))
+// Output: "5 minutes ago" in the 'en-US' locale
$switchLocaleRoute
(locale: string) => RouteLocationRaw
string
— Target locale.// on /en/news
+const routeFr = $switchLocaleRoute('fr')
+// Output: A route object with the new locale applied, e.g., { name: 'localized-news', params: { locale: 'fr' } }
$switchLocalePath
(locale: string) => string
string
— Target locale.// on /en/news
+const routeFr = $switchLocalePath('fr')
+window.location.href = routeFr
+// Output: url with new locale applied, e.g., '/fr/nouvelles'
$switchLocale
(locale: string) => void
string
— The locale to switch to.$switchLocale('fr')
+// Output: Redirects the user to the French version of the route
$switchRoute
Version introduced: v1.27.0
(route: RouteLocationNormalizedLoaded | RouteLocationResolvedGeneric | string, toLocale?: string) => void
RouteLocationNormalizedLoaded | RouteLocationResolvedGeneric | string
— The route to which you want to switch. It can be: RouteLocationNormalizedLoaded
or RouteLocationResolvedGeneric
object.string
— The locale to switch to for the target route. If not provided, the current locale is used.Info: This method facilitates seamless switching between routes, accommodating the current locale configuration. Depending on the input, it resolves the intended route and determines the appropriate locale for redirecting the user to a localized route.
Examples:
String Path:
// Switches to the given path with the current locale
+switchRoute('/about')
String Path with Locale:
// Switches to the given path with French locale
+switchRoute('/about', 'fr')
Named Route:
// Switches to a named route with the current locale
+switchRoute({ name: 'page' })
Named Route with Locale:
// Switches to a named route and changes the locale to Spanish
+switchRoute({ name: 'page' }, 'es')
$setI18nRouteParams
(value: Record<LocaleCode, Record<string, string>> | null) => Record<LocaleCode, Record<string, string>> | null
Record<LocaleCode, Record<string, string>> | null
— params of current route for other locale// in pages/news/[id].vue
+// for en/news/1-first-article
+const { $switchLocaleRoute, $setI18nRouteParams, $defineI18nRoute } = useI18n();
+// OR
+const { $switchLocaleRoute, $setI18nRouteParams, $defineI18nRoute } = useNuxtApp();
+$defineI18nRoute({
+ localeRoutes: {
+ en: '/news/:id()',
+ fr: '/nouvelles/:id()',
+ de: '/Nachricht/:id()',
+ },
+})
+const { data: news } = await useAsyncData(\`news-\${params.id}\`, async () => {
+ let response = await $fetch("/api/getNews", {
+ query: {
+ id: params.id,
+ },
+ });
+ if (response?.localeSlugs) {
+ response.localeSlugs = {
+ en: {
+ id: '1-first-article'
+ }
+ fr: {
+ id: '1-premier-article'
+ }
+ de: {
+ id: '1-erster-Artikel'
+ }
+ }
+ $setI18nRouteParams(response?.localeSlugs);
+ }
+ return response;
+});
+$switchLocalePath('fr') // === 'fr/nouvelles/1-premier-article'
+$switchLocalePath('de') // === 'de/Nachricht/1-erster-Artikel'
$localeRoute
(to: RouteLocationRaw, locale?: string) => RouteLocationResolved
RouteLocationRaw
— The target route object.string | undefined
— Optional. The locale for the generated route.const localizedRoute = $localeRoute({ name: 'index' })
+// Output: A route object with the current locale applied, e.g., { name: 'index', params: { locale: 'fr' } }
$localePath
(to: RouteLocationRaw, locale?: string) => string
RouteLocationRaw
— The target route object.string | undefined
— Optional. The locale for the generated route.const localizedRoute = $localeRoute({ name: 'news' })
+// Output: url with new locale applied, e.g., '/en/nouvelles'
$mergeTranslations
(newTranslations: Record<string, string>) => void
Record<string, string>
— The new translations to merge.$mergeTranslations({
+ welcome: 'Bienvenue, {username}!'
+})
+// Output: Updates the translation cache with the new French translation
$defineI18nRoute
(routeDefinition: { locales?: string[] | Record<string, Record<string, TranslationObject>>, localeRoutes?: Record<string, string> }) => void
string[] | Record<string, Record<string, TranslationObject>>
— This property determines which locales are available for the route.Record<string, string> | undefined
— Optional. Custom routes for specific locales.$defineI18nRoute({
+ locales: {
+ en: { greeting: 'Hello', farewell: 'Goodbye' },
+ ru: { greeting: 'Привет', farewell: 'До свидания' },
+ },
+ localeRoutes: {
+ ru: '/localesubpage',
+ },
+})
Use Cases:
Controlling Access: By specifying available locales, you can control which routes are accessible based on the current locale, ensuring that users only see content relevant to their language.
Providing Translations: The locales
object allows for providing specific translations for each route, enhancing the user experience by delivering content in the user's preferred language.
Custom Routing: The localeRoutes
property offers flexibility in defining different paths for specific locales, which can be particularly useful in cases where certain languages or regions require unique navigational flows or URLs.
This function offers a flexible way to manage routing and localization in your Nuxt application, making it easy to tailor the user experience based on the language and region settings of your audience.
Example 1: Controlling Access Based on Locales
import { useNuxtApp } from '#imports'
+
+const { $defineI18nRoute } = useNuxtApp()
+
+$defineI18nRoute({
+ locales: ['en', 'fr', 'de'] // Only these locales are allowed for this route
+})
Example 2: Providing Translations for Locales
import { useNuxtApp } from '#imports'
+
+const { $defineI18nRoute } = useNuxtApp()
+
+$defineI18nRoute({
+ locales: {
+ en: { greeting: 'Hello', farewell: 'Goodbye' },
+ fr: { greeting: 'Bonjour', farewell: 'Au revoir' },
+ de: { greeting: 'Hallo', farewell: { aaa: { bbb: "Auf Wiedersehen" } } },
+ ru: {} // Russian locale is allowed but no translations are provided
+ }
+})
📝 Explanation:
{}
) for that locale.Here's an example of how to use these methods in a Nuxt component:
<template>
+ <div>
+ <p>{{ $t('key2.key2.key2.key2.key2') }}</p>
+ <p>Current Locale: {{ $getLocale() }}</p>
+
+ <div>
+ {{ $t('welcome', { username: 'Alice', unreadCount: 5 }) }}
+ </div>
+ <div>
+ {{ $tc('apples', 10) }}
+ </div>
+
+ <div>
+ <button
+ v-for="locale in $getLocales()"
+ :key="locale"
+ :disabled="locale === $getLocale()"
+ @click="() => $switchLocale(locale.code)"
+ >
+ Switch to {{ locale.code }}
+ </button>
+ </div>
+
+ <div>
+ <NuxtLink :to="$localeRoute({ name: 'index' })">
+ Go to Index
+ </NuxtLink>
+ </div>
+ </div>
+</template>
+
+<script setup>
+import { useI18n } from '#imports'
+
+const { $getLocale, $switchLocale, $getLocales, $localeRoute, $t, $tc } = useI18n()
+</script>
useNuxtApp
Example:
import { useNuxtApp } from '#imports'
+
+const { $getLocale, $switchLocale, $getLocales, $localeRoute, $t } = useNuxtApp()
useI18n
Composable Example:
import { useI18n } from '#imports'
+
+const { $getLocale, $switchLocale, $getLocales, $localeRoute, $t } = useI18n()
+// or
+const i18n = useI18n()
<i18n-group>
Component The <i18n-group>
component in Nuxt I18n Micro provides a convenient way to group translations under a common prefix, reducing repetition and improving code organization.
prefix
String
"product.details"
, "user.profile"
groupClass
String
""
The default slot provides access to two important properties:
The slot exposes these properties through scoped slots:
<template #default="{ prefix, t }">
+ <!-- Your content here -->
+</template>
<template>
+ <i18n-group prefix="product.details">
+ <template #default="{ t }">
+ <h1>{{ t('title') }}</h1>
+ <p>{{ t('description') }}</p>
+ <div class="price">{{ t('price', { value: 99.99 }) }}</div>
+ </template>
+ </i18n-group>
+</template>
Translation file:
{
+ "product": {
+ "details": {
+ "title": "Premium Product",
+ "description": "This is a premium product",
+ "price": "Price: \${value}"
+ }
+ }
+}
<template>
+ <i18n-group
+ prefix="user.profile"
+ group-class="profile-section"
+ >
+ <template #default="{ t }">
+ <div class="user-info">
+ <h2>{{ t('title') }}</h2>
+ <p>{{ t('bio') }}</p>
+ <div class="stats">
+ <span>{{ t('stats.followers') }}</span>
+ <span>{{ t('stats.following') }}</span>
+ </div>
+ </div>
+ </template>
+ </i18n-group>
+</template>
Translation file:
{
+ "user": {
+ "profile": {
+ "title": "User Profile",
+ "bio": "User biography goes here",
+ "stats": {
+ "followers": "Followers: {count}",
+ "following": "Following: {count}"
+ }
+ }
+ }
+}
<template>
+ <i18n-group prefix="blog.post">
+ <template #default="{ t }">
+ <article>
+ <h1>{{ t('title') }}</h1>
+ <div class="meta">
+ {{ t('meta.author', { name: author }) }} |
+ {{ t('meta.date', { date: publishDate }) }}
+ </div>
+ <div v-for="(section, index) in sections" :key="index">
+ <h2>{{ t(\`sections.\${index}.title\`) }}</h2>
+ <p>{{ t(\`sections.\${index}.content\`) }}</p>
+ </div>
+ </article>
+ </template>
+ </i18n-group>
+</template>
+
+<script setup>
+const author = 'John Doe'
+const publishDate = '2024-01-01'
+const sections = ['intro', 'main', 'conclusion']
+</script>
The component wraps its content in a div with the class i18n-group
and any additional classes specified in the groupClass
prop:
.i18n-group {
+ /* Your base styles */
+}
+
+.profile-section {
+ /* Additional styles for profile sections */
+}
<i18n-group prefix="features.pricing">
+<i18n-group prefix="features.security">
<i18n-group prefix="checkout.payment">
+<i18n-group prefix="checkout.shipping">
<!-- UserProfile.vue -->
+<i18n-group prefix="user.profile">
+
+<!-- UserSettings.vue -->
+<i18n-group prefix="user.settings">
<!-- Good -->
+<i18n-group prefix="shop.product">
+
+<!-- Avoid -->
+<i18n-group prefix="shop.category.product.details.specs">
<i18n-group>
Component The <i18n-group>
component in Nuxt I18n Micro provides a convenient way to group translations under a common prefix, reducing repetition and improving code organization.
prefix
String
"product.details"
, "user.profile"
groupClass
String
""
The default slot provides access to two important properties:
The slot exposes these properties through scoped slots:
<template #default="{ prefix, t }">
+ <!-- Your content here -->
+</template>
<template>
+ <i18n-group prefix="product.details">
+ <template #default="{ t }">
+ <h1>{{ t('title') }}</h1>
+ <p>{{ t('description') }}</p>
+ <div class="price">{{ t('price', { value: 99.99 }) }}</div>
+ </template>
+ </i18n-group>
+</template>
Translation file:
{
+ "product": {
+ "details": {
+ "title": "Premium Product",
+ "description": "This is a premium product",
+ "price": "Price: \${value}"
+ }
+ }
+}
<template>
+ <i18n-group
+ prefix="user.profile"
+ group-class="profile-section"
+ >
+ <template #default="{ t }">
+ <div class="user-info">
+ <h2>{{ t('title') }}</h2>
+ <p>{{ t('bio') }}</p>
+ <div class="stats">
+ <span>{{ t('stats.followers') }}</span>
+ <span>{{ t('stats.following') }}</span>
+ </div>
+ </div>
+ </template>
+ </i18n-group>
+</template>
Translation file:
{
+ "user": {
+ "profile": {
+ "title": "User Profile",
+ "bio": "User biography goes here",
+ "stats": {
+ "followers": "Followers: {count}",
+ "following": "Following: {count}"
+ }
+ }
+ }
+}
<template>
+ <i18n-group prefix="blog.post">
+ <template #default="{ t }">
+ <article>
+ <h1>{{ t('title') }}</h1>
+ <div class="meta">
+ {{ t('meta.author', { name: author }) }} |
+ {{ t('meta.date', { date: publishDate }) }}
+ </div>
+ <div v-for="(section, index) in sections" :key="index">
+ <h2>{{ t(\`sections.\${index}.title\`) }}</h2>
+ <p>{{ t(\`sections.\${index}.content\`) }}</p>
+ </div>
+ </article>
+ </template>
+ </i18n-group>
+</template>
+
+<script setup>
+const author = 'John Doe'
+const publishDate = '2024-01-01'
+const sections = ['intro', 'main', 'conclusion']
+</script>
The component wraps its content in a div with the class i18n-group
and any additional classes specified in the groupClass
prop:
.i18n-group {
+ /* Your base styles */
+}
+
+.profile-section {
+ /* Additional styles for profile sections */
+}
<i18n-group prefix="features.pricing">
+<i18n-group prefix="features.security">
<i18n-group prefix="checkout.payment">
+<i18n-group prefix="checkout.shipping">
<!-- UserProfile.vue -->
+<i18n-group prefix="user.profile">
+
+<!-- UserSettings.vue -->
+<i18n-group prefix="user.settings">
<!-- Good -->
+<i18n-group prefix="shop.product">
+
+<!-- Avoid -->
+<i18n-group prefix="shop.category.product.details.specs">
<i18n-link>
Component The <i18n-link>
component in Nuxt I18n Micro
is a versatile link component that automatically localizes routes based on the current locale. It acts as a wrapper around the <NuxtLink>
component, providing additional features such as active link styling and support for external links.
to
NuxtLinkProps | string
<i18n-link to="/about">About Us</i18n-link>\n<i18n-link :to="{ name: 'index' }">Home</i18n-link>
activeStyle
Partial<CSSStyleDeclaration>
<i18n-link to="/about" :activeStyle="{ fontWeight: 'bold', color: 'red' }">About Us</i18n-link>
<i18n-link to="/about">About Us</i18n-link>
This example creates a link to the /about
page, localized to the current locale.
<i18n-link to="/about" :activeStyle="{ fontWeight: 'bold' }">About Us</i18n-link>
The link will have bold text when the user is on the /about
page, allowing you to style the active link directly with inline styles.
The component automatically detects external links and adds the necessary attributes for security.
<i18n-link to="https://example.com">Visit Example</i18n-link>
This link will open https://example.com
in a new tab with rel="noopener noreferrer"
applied.
The component now uses inline styles for the active state instead of a class. You can customize these styles using the activeStyle
prop.
bold
color
is specified in activeStyle
).You can override these by providing custom styles through the activeStyle
prop.
<i18n-link to="/about" :activeStyle="{ fontWeight: 'bold', color: '#42b983' }">About Us</i18n-link>
In this example, the link will be bold and green when active.
You can pass custom content inside the link using slots, making the component flexible for different use cases.
<i18n-link to="/about">\n <span>About Us</span>\n</i18n-link>
The component supports aria-label
and other accessibility attributes to ensure a more accessible experience.
<i18n-link to="/about" aria-label="Learn more about us">\n About Us\n</i18n-link>
<i18n-link>
Component The <i18n-link>
component in Nuxt I18n Micro
is a versatile link component that automatically localizes routes based on the current locale. It acts as a wrapper around the <NuxtLink>
component, providing additional features such as active link styling and support for external links.
to
NuxtLinkProps | string
<i18n-link to="/about">About Us</i18n-link>\n<i18n-link :to="{ name: 'index' }">Home</i18n-link>
activeStyle
Partial<CSSStyleDeclaration>
<i18n-link to="/about" :activeStyle="{ fontWeight: 'bold', color: 'red' }">About Us</i18n-link>
<i18n-link to="/about">About Us</i18n-link>
This example creates a link to the /about
page, localized to the current locale.
<i18n-link to="/about" :activeStyle="{ fontWeight: 'bold' }">About Us</i18n-link>
The link will have bold text when the user is on the /about
page, allowing you to style the active link directly with inline styles.
The component automatically detects external links and adds the necessary attributes for security.
<i18n-link to="https://example.com">Visit Example</i18n-link>
This link will open https://example.com
in a new tab with rel="noopener noreferrer"
applied.
The component now uses inline styles for the active state instead of a class. You can customize these styles using the activeStyle
prop.
bold
color
is specified in activeStyle
).You can override these by providing custom styles through the activeStyle
prop.
<i18n-link to="/about" :activeStyle="{ fontWeight: 'bold', color: '#42b983' }">About Us</i18n-link>
In this example, the link will be bold and green when active.
You can pass custom content inside the link using slots, making the component flexible for different use cases.
<i18n-link to="/about">\n <span>About Us</span>\n</i18n-link>
The component supports aria-label
and other accessibility attributes to ensure a more accessible experience.
<i18n-link to="/about" aria-label="Learn more about us">\n About Us\n</i18n-link>
<i18n-switcher>
Component The <i18n-switcher>
component in Nuxt I18n Micro
provides a user-friendly dropdown interface for switching between different locales in your application. This component is highly customizable, allowing seamless integration with your application's design and layout.
customLabels
Record<string, string>
{}
<i18n-switcher :customLabels="{ en: 'English', fr: 'Français' }"></i18n-switcher>
customWrapperStyle
CSSProperties
{}
<div>
that contains the locale switcher.<i18n-switcher :customWrapperStyle="{ backgroundColor: '#f8f9fa', padding: '10px' }"></i18n-switcher>
customButtonStyle
CSSProperties
{}
<i18n-switcher :customButtonStyle="{ backgroundColor: '#007bff', color: '#fff', borderRadius: '4px' }"></i18n-switcher>
customDropdownStyle
CSSProperties
{}
<ul>
element that contains the list of locales.<i18n-switcher :customDropdownStyle="{ border: '1px solid #007bff', boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)' }"></i18n-switcher>
customItemStyle
CSSProperties
{}
<li>
element representing a locale option.<i18n-switcher :customItemStyle="{ margin: '5px 0', padding: '5px' }"></i18n-switcher>
customLinkStyle
CSSProperties
{}
<NuxtLink>
elements used to switch between locales.<i18n-switcher :customLinkStyle="{ padding: '8px 16px', color: '#333', textDecoration: 'none' }"></i18n-switcher>
customActiveLinkStyle
CSSProperties
{}
<i18n-switcher :customActiveLinkStyle="{ color: 'green', fontWeight: 'bold', backgroundColor: '#f0f0f0' }"></i18n-switcher>
customDisabledLinkStyle
CSSProperties
{}
<i18n-switcher :customDisabledLinkStyle="{ color: 'gray', cursor: 'not-allowed' }"></i18n-switcher>
customIconStyle
CSSProperties
{}
<i18n-switcher :customIconStyle="{ fontSize: '20px', color: '#007bff' }"></i18n-switcher>
<template>
+ <i18n-switcher />
+</template>
This renders a locale switcher with default styling and behavior.
<template>
+ <i18n-switcher
+ :customLabels="{ en: 'English', fr: 'Français' }"
+ :customWrapperStyle="{ backgroundColor: '#f8f9fa', padding: '10px' }"
+ :customButtonStyle="{ backgroundColor: '#007bff', color: '#fff', borderRadius: '4px' }"
+ :customDropdownStyle="{ border: '1px solid #007bff', boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)' }"
+ :customItemStyle="{ margin: '5px 0', padding: '5px' }"
+ :customLinkStyle="{ padding: '8px 16px', color: '#333', textDecoration: 'none' }"
+ :customActiveLinkStyle="{ color: 'green', fontWeight: 'bold', backgroundColor: '#f0f0f0' }"
+ :customDisabledLinkStyle="{ color: 'gray', cursor: 'not-allowed' }"
+ :customIconStyle="{ fontSize: '20px', color: '#007bff' }"
+ />
+</template>
This example demonstrates a fully customized locale switcher with custom labels and inline styles.
The <i18n-switcher>
component provides several slots that allow you to insert custom content at various points within the component. These slots enhance the flexibility and customization of the switcher, enabling you to tailor it to your application's specific needs.
before-button
<i18n-switcher>
+ <template #before-button>
+ <span>🌐</span>
+ </template>
+</i18n-switcher>
before-selected-locale
<i18n-switcher>
+ <template #before-selected-locale>
+ <i class="icon-flag"></i>
+ </template>
+</i18n-switcher>
after-selected-locale
<i18n-switcher>
+ <template #after-selected-locale>
+ <i class="icon-caret"></i>
+ </template>
+</i18n-switcher>
before-dropdown
<i18n-switcher>
+ <template #before-dropdown>
+ <li class="dropdown-header">Select Language</li>
+ </template>
+</i18n-switcher>
after-dropdown
<i18n-switcher>
+ <template #after-dropdown>
+ <li class="dropdown-footer">Powered by Nuxt</li>
+ </template>
+</i18n-switcher>
before-dropdown-items
<i18n-switcher>
+ <template #before-dropdown-items>
+ <li class="divider"></li>
+ </template>
+</i18n-switcher>
after-dropdown-items
<i18n-switcher>
+ <template #after-dropdown-items>
+ <li class="divider"></li>
+ </template>
+</i18n-switcher>
before-item
locale
(Locale object)<i18n-switcher>
+ <template #before-item="{ locale }">
+ <i :class="\`flag-\${locale.code}\`"></i>
+ </template>
+</i18n-switcher>
after-item
locale
(Locale object)<i18n-switcher>
+ <template #after-item="{ locale }">
+ <span>{{ locale.code }}</span>
+ </template>
+</i18n-switcher>
before-link-content
locale
(Locale object)<i18n-switcher>
+ <template #before-link-content="{ locale }">
+ <i :class="\`icon-\${locale.code}\`"></i>
+ </template>
+</i18n-switcher>
after-link-content
locale
(Locale object)<i18n-switcher>
+ <template #after-link-content="{ locale }">
+ <span>({{ locale.code }})</span>
+ </template>
+</i18n-switcher>
Slot Name | Description | Props |
---|---|---|
before-button | Content before the language switcher button | None |
before-selected-locale | Content before the selected locale label within the button | None |
after-selected-locale | Content after the selected locale label within the button | None |
before-dropdown | Content before the dropdown menu | None |
after-dropdown | Content after the dropdown menu | None |
before-dropdown-items | Content before the list of locale items within the dropdown | None |
after-dropdown-items | Content after the list of locale items within the dropdown | None |
before-item | Content before each locale item | locale |
after-item | Content after each locale item | locale |
before-link-content | Content before the locale label inside each link | locale |
after-link-content | Content after the locale label inside each link | locale |
The <i18n-switcher>
component comes with basic styles defined using inline styles that can easily be overridden by passing custom styles via props. Here’s a brief overview of the default styling:
You can customize these styles by passing custom styles through the respective props, ensuring that the locale switcher integrates seamlessly into your application's UI.
`,58)]))}const c=i(l,[["render",n]]);export{E as __pageData,c as default}; diff --git a/assets/components_i18n-switcher.md.BVMz2Cf5.lean.js b/assets/components_i18n-switcher.md.BVMz2Cf5.lean.js new file mode 100644 index 00000000..2db1623e --- /dev/null +++ b/assets/components_i18n-switcher.md.BVMz2Cf5.lean.js @@ -0,0 +1,59 @@ +import{_ as i,c as t,a2 as a,o as e}from"./chunks/framework.Gfs4HC1t.js";const E=JSON.parse('{"title":"🌍<i18n-switcher>
Component The <i18n-switcher>
component in Nuxt I18n Micro
provides a user-friendly dropdown interface for switching between different locales in your application. This component is highly customizable, allowing seamless integration with your application's design and layout.
customLabels
Record<string, string>
{}
<i18n-switcher :customLabels="{ en: 'English', fr: 'Français' }"></i18n-switcher>
customWrapperStyle
CSSProperties
{}
<div>
that contains the locale switcher.<i18n-switcher :customWrapperStyle="{ backgroundColor: '#f8f9fa', padding: '10px' }"></i18n-switcher>
customButtonStyle
CSSProperties
{}
<i18n-switcher :customButtonStyle="{ backgroundColor: '#007bff', color: '#fff', borderRadius: '4px' }"></i18n-switcher>
customDropdownStyle
CSSProperties
{}
<ul>
element that contains the list of locales.<i18n-switcher :customDropdownStyle="{ border: '1px solid #007bff', boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)' }"></i18n-switcher>
customItemStyle
CSSProperties
{}
<li>
element representing a locale option.<i18n-switcher :customItemStyle="{ margin: '5px 0', padding: '5px' }"></i18n-switcher>
customLinkStyle
CSSProperties
{}
<NuxtLink>
elements used to switch between locales.<i18n-switcher :customLinkStyle="{ padding: '8px 16px', color: '#333', textDecoration: 'none' }"></i18n-switcher>
customActiveLinkStyle
CSSProperties
{}
<i18n-switcher :customActiveLinkStyle="{ color: 'green', fontWeight: 'bold', backgroundColor: '#f0f0f0' }"></i18n-switcher>
customDisabledLinkStyle
CSSProperties
{}
<i18n-switcher :customDisabledLinkStyle="{ color: 'gray', cursor: 'not-allowed' }"></i18n-switcher>
customIconStyle
CSSProperties
{}
<i18n-switcher :customIconStyle="{ fontSize: '20px', color: '#007bff' }"></i18n-switcher>
<template>
+ <i18n-switcher />
+</template>
This renders a locale switcher with default styling and behavior.
<template>
+ <i18n-switcher
+ :customLabels="{ en: 'English', fr: 'Français' }"
+ :customWrapperStyle="{ backgroundColor: '#f8f9fa', padding: '10px' }"
+ :customButtonStyle="{ backgroundColor: '#007bff', color: '#fff', borderRadius: '4px' }"
+ :customDropdownStyle="{ border: '1px solid #007bff', boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)' }"
+ :customItemStyle="{ margin: '5px 0', padding: '5px' }"
+ :customLinkStyle="{ padding: '8px 16px', color: '#333', textDecoration: 'none' }"
+ :customActiveLinkStyle="{ color: 'green', fontWeight: 'bold', backgroundColor: '#f0f0f0' }"
+ :customDisabledLinkStyle="{ color: 'gray', cursor: 'not-allowed' }"
+ :customIconStyle="{ fontSize: '20px', color: '#007bff' }"
+ />
+</template>
This example demonstrates a fully customized locale switcher with custom labels and inline styles.
The <i18n-switcher>
component provides several slots that allow you to insert custom content at various points within the component. These slots enhance the flexibility and customization of the switcher, enabling you to tailor it to your application's specific needs.
before-button
<i18n-switcher>
+ <template #before-button>
+ <span>🌐</span>
+ </template>
+</i18n-switcher>
before-selected-locale
<i18n-switcher>
+ <template #before-selected-locale>
+ <i class="icon-flag"></i>
+ </template>
+</i18n-switcher>
after-selected-locale
<i18n-switcher>
+ <template #after-selected-locale>
+ <i class="icon-caret"></i>
+ </template>
+</i18n-switcher>
before-dropdown
<i18n-switcher>
+ <template #before-dropdown>
+ <li class="dropdown-header">Select Language</li>
+ </template>
+</i18n-switcher>
after-dropdown
<i18n-switcher>
+ <template #after-dropdown>
+ <li class="dropdown-footer">Powered by Nuxt</li>
+ </template>
+</i18n-switcher>
before-dropdown-items
<i18n-switcher>
+ <template #before-dropdown-items>
+ <li class="divider"></li>
+ </template>
+</i18n-switcher>
after-dropdown-items
<i18n-switcher>
+ <template #after-dropdown-items>
+ <li class="divider"></li>
+ </template>
+</i18n-switcher>
before-item
locale
(Locale object)<i18n-switcher>
+ <template #before-item="{ locale }">
+ <i :class="\`flag-\${locale.code}\`"></i>
+ </template>
+</i18n-switcher>
after-item
locale
(Locale object)<i18n-switcher>
+ <template #after-item="{ locale }">
+ <span>{{ locale.code }}</span>
+ </template>
+</i18n-switcher>
before-link-content
locale
(Locale object)<i18n-switcher>
+ <template #before-link-content="{ locale }">
+ <i :class="\`icon-\${locale.code}\`"></i>
+ </template>
+</i18n-switcher>
after-link-content
locale
(Locale object)<i18n-switcher>
+ <template #after-link-content="{ locale }">
+ <span>({{ locale.code }})</span>
+ </template>
+</i18n-switcher>
Slot Name | Description | Props |
---|---|---|
before-button | Content before the language switcher button | None |
before-selected-locale | Content before the selected locale label within the button | None |
after-selected-locale | Content after the selected locale label within the button | None |
before-dropdown | Content before the dropdown menu | None |
after-dropdown | Content after the dropdown menu | None |
before-dropdown-items | Content before the list of locale items within the dropdown | None |
after-dropdown-items | Content after the list of locale items within the dropdown | None |
before-item | Content before each locale item | locale |
after-item | Content after each locale item | locale |
before-link-content | Content before the locale label inside each link | locale |
after-link-content | Content after the locale label inside each link | locale |
The <i18n-switcher>
component comes with basic styles defined using inline styles that can easily be overridden by passing custom styles via props. Here’s a brief overview of the default styling:
You can customize these styles by passing custom styles through the respective props, ensuring that the locale switcher integrates seamlessly into your application's UI.
`,58)]))}const c=i(l,[["render",n]]);export{E as __pageData,c as default}; diff --git a/assets/components_i18n-t.md.C61xRTdL.js b/assets/components_i18n-t.md.C61xRTdL.js new file mode 100644 index 00000000..e59dcdf1 --- /dev/null +++ b/assets/components_i18n-t.md.C61xRTdL.js @@ -0,0 +1,45 @@ +import{_ as i,c as a,a2 as t,o as n}from"./chunks/framework.Gfs4HC1t.js";const E=JSON.parse('{"title":"🌍<i18n-t>
Component The <i18n-t>
component in Nuxt I18n Micro
is a flexible translation component that supports dynamic content insertion via slots. It allows you to interpolate translations with custom Vue components or HTML content, enabling advanced localization scenarios.
keypath
string
<i18n-t keypath="feedback.text" />
plural
number | string
<i18n-t keypath="items" :plural="10" />
{
+ "items": "Nothing|You have {count} item|You have {count} items"
+}
number
number | string
<i18n-t keypath="data.item" :number="1234567.89" />
{
+ "data": {
+ "item": "The number is: {number}"
+ }
+}
date
Date | string | number
Date
, string, or number to render a localized date.<i18n-t keypath="data.item" :date="'2023-12-31'" />
{
+ "data": {
+ "item": "The date is: {date}"
+ }
+}
relativeDate
Date | string | number
Date
, string, or number to render a localized relative date.<i18n-t keypath="data.item" :relative-date="'2023-12-31'" />
{
+ "data": {
+ "item": "The relative date is: {relativeDate}"
+ }
+}
tag
string
'span'
<i18n-t keypath="feedback.text" tag="div" />
params
Record<string, string | number | boolean>
<i18n-t keypath="user.greeting" :params="{ name: userName }" />
defaultValue
string
<i18n-t keypath="nonExistentKey" defaultValue="Fallback text"></i18n-t>
html
boolean
false
<i18n-t keypath="feedback.text" html />
hideIfEmpty
boolean
false
true
, the component will not render anything if the translation is empty.<i18n-t keypath="optionalMessage" :hideIfEmpty="true"></i18n-t>
customPluralRule
(value: string, count: number, params: Record<string, string | number | boolean>, locale: string) => string
<i18n-t
+ keypath="items"
+ :plural="itemCount"
+ :customPluralRule="(key, count, params, locale, getTranslation) => {
+ const translation = getTranslation(key, params)
+ if (!translation) {
+ return null
+ }
+ return count === 1 ? 'no items' : \`\${count} \${translation}\`;
+ }"
+></i18n-t>
<i18n-t keypath="feedback.text" />
This renders the translation for feedback.text
within a <span>
tag.
The <i18n-t>
component supports the use of slots to dynamically insert Vue components or other content into specific parts of the translation.
<i18n-t keypath="feedback.text">
+ <template #link>
+ <nuxt-link :to="{ name: 'index' }">
+ <i18n-t keypath="feedback.link" />
+ </nuxt-link>
+ </template>
+</i18n-t>
In this example, the {link}
placeholder in the feedback.text
translation string is replaced by the <nuxt-link>
component, which itself contains another translation component.
<i18n-t keypath="items.count" :plural="itemCount" />
This automatically applies pluralization rules based on the itemCount
value.
If no specific slot is provided, the translation can be customized via the default slot, which provides the entire translated string:
<i18n-t keypath="welcome.message">
+ <template #default="{ translation }">
+ {{ translation.replace('Nuxt', 'Vue') }}
+ </template>
+</i18n-t>
Render nothing if the translation string is empty by using the hideIfEmpty
prop.
<i18n-t keypath="optionalMessage" :hideIfEmpty="true"></i18n-t>
Use a custom function to handle pluralization.
<i18n-t
+ keypath="items"
+ :plural="itemCount"
+ :customPluralRule="(key, value, count, locale) => {
+ return count === 1 ? 'One item' : \`\${count} items\`;
+ }"
+></i18n-t>
Utilize slots to customize how the translation content is rendered.
<i18n-t keypath="welcomeMessage">
+ <template #default="{ translation }">
+ <strong>{{ translation }}</strong>
+ </template>
+</i18n-t>
<i18n-t>
Component The <i18n-t>
component in Nuxt I18n Micro
is a flexible translation component that supports dynamic content insertion via slots. It allows you to interpolate translations with custom Vue components or HTML content, enabling advanced localization scenarios.
keypath
string
<i18n-t keypath="feedback.text" />
plural
number | string
<i18n-t keypath="items" :plural="10" />
{
+ "items": "Nothing|You have {count} item|You have {count} items"
+}
number
number | string
<i18n-t keypath="data.item" :number="1234567.89" />
{
+ "data": {
+ "item": "The number is: {number}"
+ }
+}
date
Date | string | number
Date
, string, or number to render a localized date.<i18n-t keypath="data.item" :date="'2023-12-31'" />
{
+ "data": {
+ "item": "The date is: {date}"
+ }
+}
relativeDate
Date | string | number
Date
, string, or number to render a localized relative date.<i18n-t keypath="data.item" :relative-date="'2023-12-31'" />
{
+ "data": {
+ "item": "The relative date is: {relativeDate}"
+ }
+}
tag
string
'span'
<i18n-t keypath="feedback.text" tag="div" />
params
Record<string, string | number | boolean>
<i18n-t keypath="user.greeting" :params="{ name: userName }" />
defaultValue
string
<i18n-t keypath="nonExistentKey" defaultValue="Fallback text"></i18n-t>
html
boolean
false
<i18n-t keypath="feedback.text" html />
hideIfEmpty
boolean
false
true
, the component will not render anything if the translation is empty.<i18n-t keypath="optionalMessage" :hideIfEmpty="true"></i18n-t>
customPluralRule
(value: string, count: number, params: Record<string, string | number | boolean>, locale: string) => string
<i18n-t
+ keypath="items"
+ :plural="itemCount"
+ :customPluralRule="(key, count, params, locale, getTranslation) => {
+ const translation = getTranslation(key, params)
+ if (!translation) {
+ return null
+ }
+ return count === 1 ? 'no items' : \`\${count} \${translation}\`;
+ }"
+></i18n-t>
<i18n-t keypath="feedback.text" />
This renders the translation for feedback.text
within a <span>
tag.
The <i18n-t>
component supports the use of slots to dynamically insert Vue components or other content into specific parts of the translation.
<i18n-t keypath="feedback.text">
+ <template #link>
+ <nuxt-link :to="{ name: 'index' }">
+ <i18n-t keypath="feedback.link" />
+ </nuxt-link>
+ </template>
+</i18n-t>
In this example, the {link}
placeholder in the feedback.text
translation string is replaced by the <nuxt-link>
component, which itself contains another translation component.
<i18n-t keypath="items.count" :plural="itemCount" />
This automatically applies pluralization rules based on the itemCount
value.
If no specific slot is provided, the translation can be customized via the default slot, which provides the entire translated string:
<i18n-t keypath="welcome.message">
+ <template #default="{ translation }">
+ {{ translation.replace('Nuxt', 'Vue') }}
+ </template>
+</i18n-t>
Render nothing if the translation string is empty by using the hideIfEmpty
prop.
<i18n-t keypath="optionalMessage" :hideIfEmpty="true"></i18n-t>
Use a custom function to handle pluralization.
<i18n-t
+ keypath="items"
+ :plural="itemCount"
+ :customPluralRule="(key, value, count, locale) => {
+ return count === 1 ? 'One item' : \`\${count} items\`;
+ }"
+></i18n-t>
Utilize slots to customize how the translation content is rendered.
<i18n-t keypath="welcomeMessage">
+ <template #default="{ translation }">
+ <strong>{{ translation }}</strong>
+ </template>
+</i18n-t>
useI18n
Composable The useI18n
composable in Nuxt I18n Micro
is designed to provide an easy and efficient way to access internationalization functionalities within your Nuxt application. It offers a variety of methods to handle localization, translation, and route management based on the current locale.
All methods can be accessed both with and without the $
prefix for convenience.
The useI18n
composable returns an object containing several key methods and properties for managing internationalization:
$getLocale
() => string
const { $getLocale } = useI18n()\nconst locale = $getLocale()\nconsole.log(locale) // e.g., 'en'
$getLocaleName
Version introduced: v1.28.0
() => string | null
const locale = $getLocaleName()\n// Output: 'English'
$getLocales
() => Locale[]
const { $getLocales } = useI18n()\nconst locales = $getLocales()\nconsole.log(locales) // e.g., [{ code: 'en', iso: 'en-US' }, { code: 'fr', iso: 'fr-FR' }]
$t
<T extends Record<string, string | number | boolean>>(key: string, params?: T, defaultValue?: string) => string | number | boolean | Translations | PluralTranslations | unknown[] | unknown | null
const { $t } = useI18n()\nconst greeting = $t('hello', { name: 'John' }, 'Hello!')\nconsole.log(greeting) // e.g., 'Hello, John'
$tc
(key: string, count: number, defaultValue?: string) => string
const { $tc } = useI18n()\nconst message = $tc('apples', 3, '3 apples')\nconsole.log(message) // e.g., '3 apples'
$has
(key: string) => boolean
const { $has } = useI18n()\nconst exists = $has('hello')\nconsole.log(exists) // e.g., true
$mergeTranslations
(newTranslations: Translations) => void
const { $mergeTranslations } = useI18n()\n$mergeTranslations({\n hello: 'Hello World',\n})
$switchLocale
(locale: string) => void
const { $switchLocale } = useI18n()\n$switchLocale('fr')
$localeRoute
(to: RouteLocationRaw, locale?: string) => RouteLocationRaw
const { $localeRoute } = useI18n()\nconst route = $localeRoute('/about', 'fr')
$loadPageTranslations
(locale: string, routeName: string) => Promise<void>
const { $loadPageTranslations } = useI18n()\nawait $loadPageTranslations('fr', 'home')
Retrieve the current locale of the application.
const { $getLocale } = useI18n()\nconst locale = $getLocale()
Translate a string with dynamic parameters, with a fallback default value.
const { $t } = useI18n()\nconst welcomeMessage = $t('welcome', { name: 'Jane' }, 'Welcome!')
Switch the application to a different locale.
const { $switchLocale } = useI18n()\n$switchLocale('de')
Generate a route localized to the current or specified locale.
const { $localeRoute } = useI18n()\nconst route = $localeRoute('/about', 'fr')
Lazy-load translations for a specific page and locale.
const { $loadPageTranslations } = useI18n()\nawait $loadPageTranslations('de', 'dashboard')
useI18n
Composable The useI18n
composable in Nuxt I18n Micro
is designed to provide an easy and efficient way to access internationalization functionalities within your Nuxt application. It offers a variety of methods to handle localization, translation, and route management based on the current locale.
All methods can be accessed both with and without the $
prefix for convenience.
The useI18n
composable returns an object containing several key methods and properties for managing internationalization:
$getLocale
() => string
const { $getLocale } = useI18n()\nconst locale = $getLocale()\nconsole.log(locale) // e.g., 'en'
$getLocaleName
Version introduced: v1.28.0
() => string | null
const locale = $getLocaleName()\n// Output: 'English'
$getLocales
() => Locale[]
const { $getLocales } = useI18n()\nconst locales = $getLocales()\nconsole.log(locales) // e.g., [{ code: 'en', iso: 'en-US' }, { code: 'fr', iso: 'fr-FR' }]
$t
<T extends Record<string, string | number | boolean>>(key: string, params?: T, defaultValue?: string) => string | number | boolean | Translations | PluralTranslations | unknown[] | unknown | null
const { $t } = useI18n()\nconst greeting = $t('hello', { name: 'John' }, 'Hello!')\nconsole.log(greeting) // e.g., 'Hello, John'
$tc
(key: string, count: number, defaultValue?: string) => string
const { $tc } = useI18n()\nconst message = $tc('apples', 3, '3 apples')\nconsole.log(message) // e.g., '3 apples'
$has
(key: string) => boolean
const { $has } = useI18n()\nconst exists = $has('hello')\nconsole.log(exists) // e.g., true
$mergeTranslations
(newTranslations: Translations) => void
const { $mergeTranslations } = useI18n()\n$mergeTranslations({\n hello: 'Hello World',\n})
$switchLocale
(locale: string) => void
const { $switchLocale } = useI18n()\n$switchLocale('fr')
$localeRoute
(to: RouteLocationRaw, locale?: string) => RouteLocationRaw
const { $localeRoute } = useI18n()\nconst route = $localeRoute('/about', 'fr')
$loadPageTranslations
(locale: string, routeName: string) => Promise<void>
const { $loadPageTranslations } = useI18n()\nawait $loadPageTranslations('fr', 'home')
Retrieve the current locale of the application.
const { $getLocale } = useI18n()\nconst locale = $getLocale()
Translate a string with dynamic parameters, with a fallback default value.
const { $t } = useI18n()\nconst welcomeMessage = $t('welcome', { name: 'Jane' }, 'Welcome!')
Switch the application to a different locale.
const { $switchLocale } = useI18n()\n$switchLocale('de')
Generate a route localized to the current or specified locale.
const { $localeRoute } = useI18n()\nconst route = $localeRoute('/about', 'fr')
Lazy-load translations for a specific page and locale.
const { $loadPageTranslations } = useI18n()\nawait $loadPageTranslations('de', 'dashboard')
useLocaleHead
Composable The useLocaleHead
composable is a utility in Nuxt I18n Micro
that helps you manage SEO attributes and HTML meta tags for localized routes. It dynamically generates attributes for the lang
and dir
of the HTML document and creates meta
and link
tags to improve the SEO of your localized content.
The useLocaleHead
composable accepts an options object to customize its behavior:
addDirAttribute
boolean
true
true
, adds the dir
attribute to the HTML document based on the current locale's direction (ltr
or rtl
).const head = useLocaleHead({ addDirAttribute: false })
identifierAttribute
string
'id'
const head = useLocaleHead({ identifierAttribute: 'data-i18n' })
addSeoAttributes
boolean
true
true
, includes SEO-related meta and link tags, such as og:locale
, og:url
, and hreflang
attributes for alternate languages.const head = useLocaleHead({ addSeoAttributes: false })
baseUrl
string
'/'
const head = useLocaleHead({ baseUrl: 'https://example.com' })
The useLocaleHead
composable returns an object with htmlAttrs
, meta
, and link
properties, which can be directly used in the <head>
section of your Nuxt application.
htmlAttrs
Record<string, string>
<html>
tag, such as lang
and dir
.const { htmlAttrs } = useLocaleHead()
+console.log(htmlAttrs)
+// Output: { lang: 'en-US', dir: 'ltr' }
meta
Array<Record<string, string>>
const { meta } = useLocaleHead()
+console.log(meta)
+// Output: [{ id: 'i18n-og', property: 'og:locale', content: 'en-US' }, ...]
link
Array<Record<string, string>>
const { link } = useLocaleHead()
+console.log(link)
+// Output: [{ id: 'i18n-can', rel: 'canonical', href: 'https://example.com/about' }, ...]
Generate locale-specific head attributes with default options.
const head = useLocaleHead()
Use a custom identifier attribute for the generated tags.
const head = useLocaleHead({ identifierAttribute: 'data-i18n' })
Generate head attributes without adding SEO-related meta and link tags.
const head = useLocaleHead({ addSeoAttributes: false })
Set a custom base URL for canonical and alternate URLs.
const head = useLocaleHead({ baseUrl: 'https://mywebsite.com' })
When addSeoAttributes
is enabled, the composable automatically generates the following tags:
og:locale
for the current locale.og:url
for the canonical URL of the page.og:locale:alternate
for alternate language versions.rel="canonical"
and rel="alternate"
links for SEO optimization.The composable dynamically determines the lang
and dir
attributes based on the current route's locale, ensuring that your HTML document is correctly configured for international users.
If your routes are prefixed with locale codes (e.g., /en/about
), the composable intelligently adjusts the full path for generating URLs, ensuring that SEO attributes are accurate and relevant.
This composable simplifies the process of optimizing your Nuxt application for international audiences, ensuring that your site is well-prepared for global search engines and users.
The following example demonstrates how to use the useLocaleHead
composable within a Vue component with default settings:
<script setup>
+const head = useLocaleHead({
+ addDirAttribute: true,
+ identifierAttribute: 'id',
+ addSeoAttributes: true,
+})
+
+useHead(head)
+</script>
+
+<template>
+ <div>
+
+ </div>
+</template>
useLocaleHead
Composable: This composable is called in the <script setup>
section and returns an object containing htmlAttrs
, meta
, and link
.
<html>
Tag: The lang
and dir
attributes for the HTML document are dynamically determined based on the current locale and are applied to the <html>
tag.
<head>
Section:
og:locale
, og:url
, and rel="canonical"
and rel="alternate"
tags to specify alternate language versions of the page.<body>
Section: The main content of the page is displayed here. In this example, a simple header and paragraph are used.
Attributes: The attributes used (lang
, dir
, rel
, href
, hreflang
, property
, content
) are extracted from the object returned by useLocaleHead
.
SEO Tags Generation: If the addSeoAttributes
option is set to true
, the composable automatically generates SEO tags for the current locale.
Base URL: You can set your custom base URL using the baseUrl
option to correctly generate canonical and alternate links.
This example demonstrates how easy it is to integrate useLocaleHead
into your application's components to ensure correct SEO attributes and improve the search engine indexing of localized pages.
useLocaleHead
Composable The useLocaleHead
composable is a utility in Nuxt I18n Micro
that helps you manage SEO attributes and HTML meta tags for localized routes. It dynamically generates attributes for the lang
and dir
of the HTML document and creates meta
and link
tags to improve the SEO of your localized content.
The useLocaleHead
composable accepts an options object to customize its behavior:
addDirAttribute
boolean
true
true
, adds the dir
attribute to the HTML document based on the current locale's direction (ltr
or rtl
).const head = useLocaleHead({ addDirAttribute: false })
identifierAttribute
string
'id'
const head = useLocaleHead({ identifierAttribute: 'data-i18n' })
addSeoAttributes
boolean
true
true
, includes SEO-related meta and link tags, such as og:locale
, og:url
, and hreflang
attributes for alternate languages.const head = useLocaleHead({ addSeoAttributes: false })
baseUrl
string
'/'
const head = useLocaleHead({ baseUrl: 'https://example.com' })
The useLocaleHead
composable returns an object with htmlAttrs
, meta
, and link
properties, which can be directly used in the <head>
section of your Nuxt application.
htmlAttrs
Record<string, string>
<html>
tag, such as lang
and dir
.const { htmlAttrs } = useLocaleHead()
+console.log(htmlAttrs)
+// Output: { lang: 'en-US', dir: 'ltr' }
meta
Array<Record<string, string>>
const { meta } = useLocaleHead()
+console.log(meta)
+// Output: [{ id: 'i18n-og', property: 'og:locale', content: 'en-US' }, ...]
link
Array<Record<string, string>>
const { link } = useLocaleHead()
+console.log(link)
+// Output: [{ id: 'i18n-can', rel: 'canonical', href: 'https://example.com/about' }, ...]
Generate locale-specific head attributes with default options.
const head = useLocaleHead()
Use a custom identifier attribute for the generated tags.
const head = useLocaleHead({ identifierAttribute: 'data-i18n' })
Generate head attributes without adding SEO-related meta and link tags.
const head = useLocaleHead({ addSeoAttributes: false })
Set a custom base URL for canonical and alternate URLs.
const head = useLocaleHead({ baseUrl: 'https://mywebsite.com' })
When addSeoAttributes
is enabled, the composable automatically generates the following tags:
og:locale
for the current locale.og:url
for the canonical URL of the page.og:locale:alternate
for alternate language versions.rel="canonical"
and rel="alternate"
links for SEO optimization.The composable dynamically determines the lang
and dir
attributes based on the current route's locale, ensuring that your HTML document is correctly configured for international users.
If your routes are prefixed with locale codes (e.g., /en/about
), the composable intelligently adjusts the full path for generating URLs, ensuring that SEO attributes are accurate and relevant.
This composable simplifies the process of optimizing your Nuxt application for international audiences, ensuring that your site is well-prepared for global search engines and users.
The following example demonstrates how to use the useLocaleHead
composable within a Vue component with default settings:
<script setup>
+const head = useLocaleHead({
+ addDirAttribute: true,
+ identifierAttribute: 'id',
+ addSeoAttributes: true,
+})
+
+useHead(head)
+</script>
+
+<template>
+ <div>
+
+ </div>
+</template>
useLocaleHead
Composable: This composable is called in the <script setup>
section and returns an object containing htmlAttrs
, meta
, and link
.
<html>
Tag: The lang
and dir
attributes for the HTML document are dynamically determined based on the current locale and are applied to the <html>
tag.
<head>
Section:
og:locale
, og:url
, and rel="canonical"
and rel="alternate"
tags to specify alternate language versions of the page.<body>
Section: The main content of the page is displayed here. In this example, a simple header and paragraph are used.
Attributes: The attributes used (lang
, dir
, rel
, href
, hreflang
, property
, content
) are extracted from the object returned by useLocaleHead
.
SEO Tags Generation: If the addSeoAttributes
option is set to true
, the composable automatically generates SEO tags for the current locale.
Base URL: You can set your custom base URL using the baseUrl
option to correctly generate canonical and alternate links.
This example demonstrates how easy it is to integrate useLocaleHead
into your application's components to ensure correct SEO attributes and improve the search engine indexing of localized pages.
This section provides various examples demonstrating how to use Nuxt I18n Micro
in your Nuxt.js application. You'll see how to switch locales, use the <i18n-link>
, <i18n-switcher>
, and <i18n-t>
components, and dynamically handle translation keys.
Here's a basic setup to get started with Nuxt I18n Micro
:
export default defineNuxtConfig({
+ modules: ['nuxt-i18n-micro'],
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-US', dir: 'ltr', disabled: false, displayName: 'English' },
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr', disabled: false, displayName: 'Français' },
+ { code: 'de', iso: 'de-DE', dir: 'ltr', disabled: false, displayName: 'Deutsch' },
+ ],
+ defaultLocale: 'en',
+ translationDir: 'locales',
+ meta: true,
+ },
+})
This example demonstrates how to switch locales programmatically using buttons:
<template>
+ <div>
+ <p>Current Locale: {{ $getLocale() }}</p>
+ <div>
+ <button
+ v-for="locale in $getLocales()"
+ :key="locale.code"
+ :disabled="locale.code === $getLocale()"
+ @click="() => $switchLocale(locale.code)"
+ >
+ Switch to {{ $t(locale.code) }}
+ </button>
+ </div>
+ </div>
+</template>
+
+<script setup>
+import { useNuxtApp } from '#imports'
+
+const { $getLocale, $switchLocale, $getLocales, $t } = useNuxtApp()
+</script>
{
+ "en": "English",
+ "fr": "Français",
+ "de": "Deutsch"
+}
<i18n-switcher>
Component The <i18n-switcher>
component provides a dropdown for locale switching with customizable labels:
<template>
+ <div>
+ <i18n-switcher
+ :custom-labels="{ en: 'English', fr: 'Français', de: 'Deutsch' }"
+ />
+ </div>
+</template>
<i18n-link>
for Localized Navigation The <i18n-link>
component automatically handles locale-specific routing:
<template>
+ <div>
+ <i18n-link to="/about">{{ $t('about') }}</i18n-link>
+ <i18n-link :to="{ name: 'index' }">{{ $t('home') }}</i18n-link>
+ </div>
+</template>
+
+<script setup>
+ import { useNuxtApp } from '#imports'
+
+ const { $getLocale, $switchLocale, $getLocales, $t } = useNuxtApp()
+</script>
{
+ "about": "About Us",
+ "home": "Home"
+}
<template>
+ <div>
+ <i18n-link to="/about" activeClass="current">About Us</i18n-link>
+ </div>
+</template>
The same JSON file can be used as in the previous example for this scenario.
In some scenarios, you may want to iterate over dynamic keys stored within your translation files and render their values conditionally. The example below demonstrates how to achieve this using Nuxt I18n Micro
.
This example fetches an array of keys from a specific translation path (in this case, dynamic
) and iterates over them. Each key is checked for its existence using $has
before rendering its value with $t
.
<template>
+ <div>
+ <div
+ v-for="key in $t('dynamic')"
+ :key="key"
+ >
+ <p>{{ key }}: <span v-if="$has(key)">{{ $t(key) }}</span></p>
+ </div>
+ </div>
+</template>
+
+<script setup>
+import { useNuxtApp } from '#imports'
+
+const { $t, $has } = useNuxtApp()
+</script>
en.json
) {
+ "dynamic": ["key1", "key2", "key3"],
+ "key1": "This is the first key's value",
+ "key2": "This is the second key's value",
+ "key3": "This is the third key's value"
+}
In this example, we handle an object stored within your translation file. We fetch and iterate over the keys of the object, dynamically rendering both the key names and their associated values.
<template>
+ <div>
+ <div v-for="(value, key) in $t('dynamicObject')" :key="key">
+ <p>{{ key }}: {{ value }}</p>
+ </div>
+ </div>
+</template>
+
+<script setup>
+import { useNuxtApp } from '#imports'
+
+const { $t } = useNuxtApp()
+</script>
en.json
) {
+ "dynamicObject": {
+ "title": "Welcome to our site",
+ "description": "This is a brief description of our services.",
+ "footerNote": "Thank you for visiting!"
+ }
+}
<i18n-t>
for Translations with Slots and Interpolation The <i18n-t>
component is useful for rendering translations with dynamic content and HTML tags:
<template>
+ <i18n-t keypath="greeting" tag="h1">
+ <template #default="{ translation }">
+ <strong>{{ translation.replace('page', 'page replace') }}</strong> <i>!!!</i>
+ </template>
+ </i18n-t>
+</template>
<i18n-t>
{
+ "greeting": "Welcome to the page"
+}
<template>
+ <i18n-t keypath="welcome" :params="{ username: 'Alice', unreadCount: 5 }"></i18n-t>
+</template>
{
+ "welcome": "Hello {username}, you have {unreadCount} unread messages."
+}
Here's a complex structure demonstrating multiple translation uses within a single page:
<template>
+ <div>
+ <h1>{{ $t('mainHeader') }}</h1>
+
+ <nav>
+ <ul>
+ <li><a href="#">{{ $t('nav.home') }}</a></li>
+ <li><a href="#">{{ $t('nav.about') }}</a></li>
+ <li><a href="#">{{ $t('nav.services') }}</a></li>
+ <li><a href="#">{{ $t('nav.contact') }}</a></li>
+ </ul>
+ </nav>
+
+ <section>
+ <h2>{{ $t('section1.header') }}</h2>
+ <p>{{ $t('section1.intro') }}</p>
+
+ <div>
+ <h3>{{ $t('section1.subsection1.header') }}</h3>
+ <p>{{ $t('section1.subsection1.content') }}</p>
+ </div>
+
+ <div>
+ <h3>{{ $t('section1.subsection2.header') }}</h3>
+ <ul>
+ <li>{{ $t('section1.subsection2.item1') }}</li>
+ <li>{{ $t('section1.subsection2.item2') }}</li>
+ <li>{{ $t('section1.subsection2.item3') }}</li>
+ </ul>
+ </div>
+ </section>
+
+ <footer>
+ <h4>{{ $t('footer.contact.header') }}</h4>
+ <address>
+ {{ $t('footer.contact.address') }}<br>
+ {{ $t('footer.contact.city') }}<br>
+ {{ $t('footer.contact.phone') }}
+ </address>
+ </footer>
+
+ <div>
+ <button
+ v-for="locale in $getLocales()"
+ :key="locale.code"
+ :disabled="locale.code === $getLocale()"
+ @click="() => $switchLocale(locale.code)"
+ >
+ Switch to {{ locale.code }}
+ </button>
+ </div>
+ </div>
+</template>
+
+<script setup>
+import { useNuxtApp } from '#imports'
+
+const { $getLocale, $switchLocale, $getLocales, $t } = useNuxtApp()
+</script>
{
+ "mainHeader": "Welcome to Our Services",
+ "nav": {
+ "home": "Home",
+ "about": "About Us",
+ "services": "Services",
+ "contact": "Contact"
+ },
+ "section1": {
+ "header": "Our Expertise",
+ "intro": "We provide a wide range of services to meet your needs.",
+ "subsection1": {
+ "header": "Consulting",
+ "content": "Our team offers expert consulting services in various domains."
+ },
+ "subsection2": {
+ "header": "Development",
+ "item1":
+
+ "Web Development",
+ "item2": "Mobile Apps",
+ "item3": "Custom Software"
+ }
+ },
+ "footer": {
+ "contact": {
+ "header": "Contact Us",
+ "address": "123 Main Street",
+ "city": "Anytown, USA",
+ "phone": "+1 (555) 123-4567"
+ }
+ }
+}
$tc
for Pluralization The $tc
function in Nuxt I18n Micro
handles pluralization based on the count and locale settings. This is useful for dynamically adjusting messages that involve counts, such as items, notifications, or other entities that can vary in number.
$tc
for Pluralization In the following example, we display a message indicating the number of apples using $tc
. The translation key handles multiple plural forms based on the count provided.
<template>
+ <div>
+ <!-- Display a pluralized message about the number of apples -->
+ <p>{{ $tc('apples', 0) }}</p> <!-- Outputs: no apples -->
+ <p>{{ $tc('apples', 1) }}</p> <!-- Outputs: one apple -->
+ <p>{{ $tc('apples', 10) }}</p> <!-- Outputs: 10 apples -->
+ </div>
+</template>
+
+<script setup>
+import { useNuxtApp } from '#imports'
+
+const { $tc } = useNuxtApp()
+</script>
Here's how you can define the translation in your JSON file to handle different plural forms:
{
+ "apples": "no apples | one apple | {count} apples"
+}
$tc('apples', 0)
: Returns the first form, used when the count is zero ("no apples"
).$tc('apples', 1)
: Returns the second form, used when the count is one ("one apple"
).$tc('apples', 10)
: Returns the third form with the count value, used when the count is two or more ("10 apples"
).If your application needs to handle more complex pluralization rules (e.g., specific cases for zero, one, two, few, many, other), you can extend the translation strings accordingly:
{
+ "apples": "no apples | one apple | two apples | a few apples | many apples | {count} apples"
+}
$tc('apples', 2)
: Could be set up to return "two apples"
.$tc('apples', 3)
: Could return "a few apples"
, depending on the rules defined for the count.$tn
for Number Formatting The $tn
function formats numbers according to the current locale using the Intl.NumberFormat
API. This is useful for displaying numbers in a way that matches the user's regional settings, such as currency, percentages, or other number formats.
$tn
for Number Formatting <template>
+ <div>
+ <!-- Format a number as currency -->
+ <p>{{ $tn(1234567.89, { style: 'currency', currency: 'USD' }) }}</p> <!-- Outputs: $1,234,567.89 in 'en-US' locale -->
+
+ <!-- Format a number with custom options -->
+ <p>{{ $tn(0.567, { style: 'percent', minimumFractionDigits: 1 }) }}</p> <!-- Outputs: 56.7% in 'en-US' locale -->
+ </div>
+</template>
+
+<script setup>
+import { useNuxtApp } from '#imports'
+
+const { $tn } = useNuxtApp()
+</script>
$td
for Date and Time Formatting The $td
function formats dates and times according to the current locale using the Intl.DateTimeFormat
API. This is useful for displaying dates and times in formats that are familiar to the user based on their locale settings.
$td
for Date and Time Formatting <template>
+ <div>
+ <!-- Format a date with full options -->
+ <p>{{ $td(new Date(), { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }) }}</p> <!-- Outputs: "Friday, September 1, 2023" in 'en-US' locale -->
+
+ <!-- Format a date with time -->
+ <p>{{ $td(new Date(), { hour: '2-digit', minute: '2-digit', second: '2-digit' }) }}</p> <!-- Outputs: "10:15:30 AM" in 'en-US' locale -->
+ </div>
+</template>
+
+<script setup>
+import { useNuxtApp } from '#imports'
+
+const { $td } = useNuxtApp()
+</script>
$tdr
for Relative Date Formatting The $tdr
function formats dates as relative times (e.g., "5 minutes ago", "2 days ago") according to the current locale using the Intl.RelativeTimeFormat
API. This is useful for displaying time differences relative to the current date and time.
$tdr
for Relative Date Formatting <template>
+ <div>
+ <!-- Format a date as a relative time -->
+ <p>{{ $tdr(new Date(Date.now() - 1000 * 60 * 5)) }}</p> <!-- Outputs: "5 minutes ago" in 'en-US' locale -->
+
+ <!-- Format a date that is in the future -->
+ <p>{{ $tdr(new Date(Date.now() + 1000 * 60 * 60 * 24)) }}</p> <!-- Outputs: "in 1 day" in 'en-US' locale -->
+ </div>
+</template>
+
+<script setup>
+import { useNuxtApp } from '#imports'
+
+const { $tdr } = useNuxtApp()
+</script>
This section provides various examples demonstrating how to use Nuxt I18n Micro
in your Nuxt.js application. You'll see how to switch locales, use the <i18n-link>
, <i18n-switcher>
, and <i18n-t>
components, and dynamically handle translation keys.
Here's a basic setup to get started with Nuxt I18n Micro
:
export default defineNuxtConfig({
+ modules: ['nuxt-i18n-micro'],
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-US', dir: 'ltr', disabled: false, displayName: 'English' },
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr', disabled: false, displayName: 'Français' },
+ { code: 'de', iso: 'de-DE', dir: 'ltr', disabled: false, displayName: 'Deutsch' },
+ ],
+ defaultLocale: 'en',
+ translationDir: 'locales',
+ meta: true,
+ },
+})
This example demonstrates how to switch locales programmatically using buttons:
<template>
+ <div>
+ <p>Current Locale: {{ $getLocale() }}</p>
+ <div>
+ <button
+ v-for="locale in $getLocales()"
+ :key="locale.code"
+ :disabled="locale.code === $getLocale()"
+ @click="() => $switchLocale(locale.code)"
+ >
+ Switch to {{ $t(locale.code) }}
+ </button>
+ </div>
+ </div>
+</template>
+
+<script setup>
+import { useNuxtApp } from '#imports'
+
+const { $getLocale, $switchLocale, $getLocales, $t } = useNuxtApp()
+</script>
{
+ "en": "English",
+ "fr": "Français",
+ "de": "Deutsch"
+}
<i18n-switcher>
Component The <i18n-switcher>
component provides a dropdown for locale switching with customizable labels:
<template>
+ <div>
+ <i18n-switcher
+ :custom-labels="{ en: 'English', fr: 'Français', de: 'Deutsch' }"
+ />
+ </div>
+</template>
<i18n-link>
for Localized Navigation The <i18n-link>
component automatically handles locale-specific routing:
<template>
+ <div>
+ <i18n-link to="/about">{{ $t('about') }}</i18n-link>
+ <i18n-link :to="{ name: 'index' }">{{ $t('home') }}</i18n-link>
+ </div>
+</template>
+
+<script setup>
+ import { useNuxtApp } from '#imports'
+
+ const { $getLocale, $switchLocale, $getLocales, $t } = useNuxtApp()
+</script>
{
+ "about": "About Us",
+ "home": "Home"
+}
<template>
+ <div>
+ <i18n-link to="/about" activeClass="current">About Us</i18n-link>
+ </div>
+</template>
The same JSON file can be used as in the previous example for this scenario.
In some scenarios, you may want to iterate over dynamic keys stored within your translation files and render their values conditionally. The example below demonstrates how to achieve this using Nuxt I18n Micro
.
This example fetches an array of keys from a specific translation path (in this case, dynamic
) and iterates over them. Each key is checked for its existence using $has
before rendering its value with $t
.
<template>
+ <div>
+ <div
+ v-for="key in $t('dynamic')"
+ :key="key"
+ >
+ <p>{{ key }}: <span v-if="$has(key)">{{ $t(key) }}</span></p>
+ </div>
+ </div>
+</template>
+
+<script setup>
+import { useNuxtApp } from '#imports'
+
+const { $t, $has } = useNuxtApp()
+</script>
en.json
) {
+ "dynamic": ["key1", "key2", "key3"],
+ "key1": "This is the first key's value",
+ "key2": "This is the second key's value",
+ "key3": "This is the third key's value"
+}
In this example, we handle an object stored within your translation file. We fetch and iterate over the keys of the object, dynamically rendering both the key names and their associated values.
<template>
+ <div>
+ <div v-for="(value, key) in $t('dynamicObject')" :key="key">
+ <p>{{ key }}: {{ value }}</p>
+ </div>
+ </div>
+</template>
+
+<script setup>
+import { useNuxtApp } from '#imports'
+
+const { $t } = useNuxtApp()
+</script>
en.json
) {
+ "dynamicObject": {
+ "title": "Welcome to our site",
+ "description": "This is a brief description of our services.",
+ "footerNote": "Thank you for visiting!"
+ }
+}
<i18n-t>
for Translations with Slots and Interpolation The <i18n-t>
component is useful for rendering translations with dynamic content and HTML tags:
<template>
+ <i18n-t keypath="greeting" tag="h1">
+ <template #default="{ translation }">
+ <strong>{{ translation.replace('page', 'page replace') }}</strong> <i>!!!</i>
+ </template>
+ </i18n-t>
+</template>
<i18n-t>
{
+ "greeting": "Welcome to the page"
+}
<template>
+ <i18n-t keypath="welcome" :params="{ username: 'Alice', unreadCount: 5 }"></i18n-t>
+</template>
{
+ "welcome": "Hello {username}, you have {unreadCount} unread messages."
+}
Here's a complex structure demonstrating multiple translation uses within a single page:
<template>
+ <div>
+ <h1>{{ $t('mainHeader') }}</h1>
+
+ <nav>
+ <ul>
+ <li><a href="#">{{ $t('nav.home') }}</a></li>
+ <li><a href="#">{{ $t('nav.about') }}</a></li>
+ <li><a href="#">{{ $t('nav.services') }}</a></li>
+ <li><a href="#">{{ $t('nav.contact') }}</a></li>
+ </ul>
+ </nav>
+
+ <section>
+ <h2>{{ $t('section1.header') }}</h2>
+ <p>{{ $t('section1.intro') }}</p>
+
+ <div>
+ <h3>{{ $t('section1.subsection1.header') }}</h3>
+ <p>{{ $t('section1.subsection1.content') }}</p>
+ </div>
+
+ <div>
+ <h3>{{ $t('section1.subsection2.header') }}</h3>
+ <ul>
+ <li>{{ $t('section1.subsection2.item1') }}</li>
+ <li>{{ $t('section1.subsection2.item2') }}</li>
+ <li>{{ $t('section1.subsection2.item3') }}</li>
+ </ul>
+ </div>
+ </section>
+
+ <footer>
+ <h4>{{ $t('footer.contact.header') }}</h4>
+ <address>
+ {{ $t('footer.contact.address') }}<br>
+ {{ $t('footer.contact.city') }}<br>
+ {{ $t('footer.contact.phone') }}
+ </address>
+ </footer>
+
+ <div>
+ <button
+ v-for="locale in $getLocales()"
+ :key="locale.code"
+ :disabled="locale.code === $getLocale()"
+ @click="() => $switchLocale(locale.code)"
+ >
+ Switch to {{ locale.code }}
+ </button>
+ </div>
+ </div>
+</template>
+
+<script setup>
+import { useNuxtApp } from '#imports'
+
+const { $getLocale, $switchLocale, $getLocales, $t } = useNuxtApp()
+</script>
{
+ "mainHeader": "Welcome to Our Services",
+ "nav": {
+ "home": "Home",
+ "about": "About Us",
+ "services": "Services",
+ "contact": "Contact"
+ },
+ "section1": {
+ "header": "Our Expertise",
+ "intro": "We provide a wide range of services to meet your needs.",
+ "subsection1": {
+ "header": "Consulting",
+ "content": "Our team offers expert consulting services in various domains."
+ },
+ "subsection2": {
+ "header": "Development",
+ "item1":
+
+ "Web Development",
+ "item2": "Mobile Apps",
+ "item3": "Custom Software"
+ }
+ },
+ "footer": {
+ "contact": {
+ "header": "Contact Us",
+ "address": "123 Main Street",
+ "city": "Anytown, USA",
+ "phone": "+1 (555) 123-4567"
+ }
+ }
+}
$tc
for Pluralization The $tc
function in Nuxt I18n Micro
handles pluralization based on the count and locale settings. This is useful for dynamically adjusting messages that involve counts, such as items, notifications, or other entities that can vary in number.
$tc
for Pluralization In the following example, we display a message indicating the number of apples using $tc
. The translation key handles multiple plural forms based on the count provided.
<template>
+ <div>
+ <!-- Display a pluralized message about the number of apples -->
+ <p>{{ $tc('apples', 0) }}</p> <!-- Outputs: no apples -->
+ <p>{{ $tc('apples', 1) }}</p> <!-- Outputs: one apple -->
+ <p>{{ $tc('apples', 10) }}</p> <!-- Outputs: 10 apples -->
+ </div>
+</template>
+
+<script setup>
+import { useNuxtApp } from '#imports'
+
+const { $tc } = useNuxtApp()
+</script>
Here's how you can define the translation in your JSON file to handle different plural forms:
{
+ "apples": "no apples | one apple | {count} apples"
+}
$tc('apples', 0)
: Returns the first form, used when the count is zero ("no apples"
).$tc('apples', 1)
: Returns the second form, used when the count is one ("one apple"
).$tc('apples', 10)
: Returns the third form with the count value, used when the count is two or more ("10 apples"
).If your application needs to handle more complex pluralization rules (e.g., specific cases for zero, one, two, few, many, other), you can extend the translation strings accordingly:
{
+ "apples": "no apples | one apple | two apples | a few apples | many apples | {count} apples"
+}
$tc('apples', 2)
: Could be set up to return "two apples"
.$tc('apples', 3)
: Could return "a few apples"
, depending on the rules defined for the count.$tn
for Number Formatting The $tn
function formats numbers according to the current locale using the Intl.NumberFormat
API. This is useful for displaying numbers in a way that matches the user's regional settings, such as currency, percentages, or other number formats.
$tn
for Number Formatting <template>
+ <div>
+ <!-- Format a number as currency -->
+ <p>{{ $tn(1234567.89, { style: 'currency', currency: 'USD' }) }}</p> <!-- Outputs: $1,234,567.89 in 'en-US' locale -->
+
+ <!-- Format a number with custom options -->
+ <p>{{ $tn(0.567, { style: 'percent', minimumFractionDigits: 1 }) }}</p> <!-- Outputs: 56.7% in 'en-US' locale -->
+ </div>
+</template>
+
+<script setup>
+import { useNuxtApp } from '#imports'
+
+const { $tn } = useNuxtApp()
+</script>
$td
for Date and Time Formatting The $td
function formats dates and times according to the current locale using the Intl.DateTimeFormat
API. This is useful for displaying dates and times in formats that are familiar to the user based on their locale settings.
$td
for Date and Time Formatting <template>
+ <div>
+ <!-- Format a date with full options -->
+ <p>{{ $td(new Date(), { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }) }}</p> <!-- Outputs: "Friday, September 1, 2023" in 'en-US' locale -->
+
+ <!-- Format a date with time -->
+ <p>{{ $td(new Date(), { hour: '2-digit', minute: '2-digit', second: '2-digit' }) }}</p> <!-- Outputs: "10:15:30 AM" in 'en-US' locale -->
+ </div>
+</template>
+
+<script setup>
+import { useNuxtApp } from '#imports'
+
+const { $td } = useNuxtApp()
+</script>
$tdr
for Relative Date Formatting The $tdr
function formats dates as relative times (e.g., "5 minutes ago", "2 days ago") according to the current locale using the Intl.RelativeTimeFormat
API. This is useful for displaying time differences relative to the current date and time.
$tdr
for Relative Date Formatting <template>
+ <div>
+ <!-- Format a date as a relative time -->
+ <p>{{ $tdr(new Date(Date.now() - 1000 * 60 * 5)) }}</p> <!-- Outputs: "5 minutes ago" in 'en-US' locale -->
+
+ <!-- Format a date that is in the future -->
+ <p>{{ $tdr(new Date(Date.now() + 1000 * 60 * 60 * 24)) }}</p> <!-- Outputs: "in 1 day" in 'en-US' locale -->
+ </div>
+</template>
+
+<script setup>
+import { useNuxtApp } from '#imports'
+
+const { $tdr } = useNuxtApp()
+</script>
nuxt-i18n-micro-cli
is a command-line tool designed to streamline the localization and internationalization process in Nuxt.js projects using the nuxt-i18n
module. It provides utilities to extract translation keys from your codebase, manage translation files, synchronize translations across locales, and automate the translation process using external translation services.
This guide will walk you through installing, configuring, and using nuxt-i18n-micro-cli
to effectively manage your project's translations. Package on npmjs.com.
Install nuxt-i18n-micro-cli
globally using npm:
npm install -g nuxt-i18n-micro-cli
This will make the i18n-micro
command available globally on your system.
After installing, you can run i18n-micro
commands in your Nuxt.js project directory.
Ensure that your project is set up with nuxt-i18n
and has the necessary configuration in nuxt.config.js
.
--cwd
: Specify the current working directory (defaults to .
).--logLevel
: Set the log level (silent
, info
, verbose
).--translationDir
: Directory containing JSON translation files (default: locales
).text-to-i18n
Command Version introduced: v1.1.0
Description: The text-to-i18n
command automatically scans your codebase for hardcoded text strings and replaces them with i18n translation references. It extracts text from Vue templates, JavaScript, and TypeScript files, generating translation keys and updating your translation files.
Usage:
i18n-micro text-to-i18n [options]
Options:
--translationFile
: Path to the JSON file containing translations (default: locales/en.json
).--context
: Context prefix for translation keys. Helps organize translations by feature or section.--dryRun
: Show changes without modifying files (default: false
).--verbose
: Show detailed processing information (default: false
).--path
: Path to a specific file to process (e.g., ./pages/test-page.vue
). When provided, only the specified file is processed.Example:
i18n-micro text-to-i18n --translationFile locales/en.json --context auth
How it works:
pages
, components
, and plugins
.vue
, .js
, and .ts
Example Transformations:
Before:
<template>\n <div>\n <h1>Welcome to our site</h1>\n <p>Please sign in to continue</p>\n </div>\n</template>
After:
<template>\n <div>\n <h1>{{ $t('pages.home.welcome_to_our_site') }}</h1>\n <p>{{ $t('pages.home.please_sign_in') }}</p>\n </div>\n</template>
Best Practices:
Run in Dry Mode First:
i18n-micro text-to-i18n --dryRun
This shows what changes would be made without modifying files.
Use Context for Organization:
i18n-micro text-to-i18n --context auth
Prefixes translation keys with auth.
for better organization.
Review Changes:
Notes:
stats
Command Description: The stats
command is used to display translation statistics for each locale in your Nuxt.js project. It helps you understand the progress of your translations by showing how many keys are translated compared to the total number of keys available.
Usage:
i18n-micro stats [options]
Options:
--full
: Display combined translations statistics only (default: false
).Example:
i18n-micro stats --full
translate
Command Description: The translate
command automatically translates missing keys using external translation services. This command simplifies the translation process by leveraging APIs from services like Google Translate, DeepL, and others to fill in missing translations.
Usage:
i18n-micro translate [options]
Options:
--service
: Translation service to use (e.g., google
, deepl
, yandex
). If not specified, the command will prompt you to select one.--token
: API key corresponding to the chosen translation service. If not provided, you will be prompted to enter it.--options
: Additional options for the translation service, provided as key:value pairs, separated by commas (e.g., model:gpt-3.5-turbo,max_tokens:1000
).--replace
: Translate all keys, replacing existing translations (default: false
).Example:
i18n-micro translate --service deepl --token YOUR_DEEPL_API_KEY
The translate
command supports multiple translation services. Some of the supported services are:
google
)deepl
)yandex
)openai
)azure
)ibm
)baidu
)libretranslate
)mymemory
)lingvatranslate
)papago
)tencent
)systran
)yandexcloud
)modernmt
)lilt
)unbabel
)reverso
)Some services require specific configurations or API keys. When using the translate
command, you can specify the service and provide the required --token
(API key) and additional --options
if needed.
For example:
i18n-micro translate --service openai --token YOUR_OPENAI_API_KEY --options openaiModel:gpt-3.5-turbo,max_tokens:1000
extract
Command Description: Extracts translation keys from your codebase and organizes them by scope.
Usage:
i18n-micro extract [options]
Options:
--prod, -p
: Run in production mode.Example:
i18n-micro extract
sync
Command Description: Synchronizes translation files across locales, ensuring all locales have the same keys.
Usage:
i18n-micro sync [options]
Example:
i18n-micro sync
validate
Command Description: Validates translation files for missing or extra keys compared to the reference locale.
Usage:
i18n-micro validate [options]
Example:
i18n-micro validate
clean
Command Description: Removes unused translation keys from translation files.
Usage:
i18n-micro clean [options]
Example:
i18n-micro clean
import
Command Description: Converts PO files back to JSON format and saves them in the translation directory.
Usage:
i18n-micro import [options]
Options:
--potsDir
: Directory containing PO files (default: pots
).Example:
i18n-micro import --potsDir pots
export
Command Description: Exports translations to PO files for external translation management.
Usage:
i18n-micro export [options]
Options:
--potsDir
: Directory to save PO files (default: pots
).Example:
i18n-micro export --potsDir pots
export-csv
Command Description: The export-csv
command exports translation keys and values from JSON files, including their file paths, into a CSV format. This command is useful for teams who prefer working with translation data in spreadsheet software.
Usage:
i18n-micro export-csv [options]
Options:
--csvDir
: Directory where the exported CSV files will be saved.--delimiter
: Specify a delimiter for the CSV file (default: ,
).Example:
i18n-micro export-csv --csvDir csv_files
import-csv
Command Description: The import-csv
command imports translation data from CSV files, updating the corresponding JSON files. This is useful for applying bulk translation updates from spreadsheets.
Usage:
i18n-micro import-csv [options]
Options:
--csvDir
: Directory containing the CSV files to be imported.--delimiter
: Specify a delimiter used in the CSV file (default: ,
).Example:
i18n-micro import-csv --csvDir csv_files
diff
Command Description: Compares translation files between the default locale and other locales within the same directory (including subdirectories). The command identifies missing keys and their values in the default locale compared to other locales, making it easier to track translation progress or discrepancies.
Usage:
i18n-micro diff [options]
Example:
i18n-micro diff
check-duplicates
Command Description: The check-duplicates
command checks for duplicate translation values within each locale across all translation files, including both global and page-specific translations. It ensures that different keys within the same language do not share identical translation values, helping maintain clarity and consistency in your translations.
Usage:
i18n-micro check-duplicates [options]
Example:
i18n-micro check-duplicates
How it works:
This command helps ensure that translation keys maintain unique values, preventing accidental repetition within the same locale.
replace-values
Command Description: The replace-values
command allows you to perform bulk replacements of translation values across all locales. It supports both simple text replacements and advanced replacements using regular expressions (regex). You can also use capturing groups in regex patterns and reference them in the replacement string, making it ideal for more complex replacement scenarios.
Usage:
i18n-micro replace-values [options]
Options:
--search
: The text or regex pattern to search for in translations. This is a required option.--replace
: The replacement text to be used for the found translations. This is a required option.--useRegex
: Enable search using a regular expression pattern (default: false
).Example 1: Simple replacement
Replace the string "Hello" with "Hi" across all locales:
i18n-micro replace-values --search "Hello" --replace "Hi"
Example 2: Regex replacement
Enable regex search and replace any string starting with "Hello" followed by numbers (e.g., "Hello123") with "Hi" across all locales:
i18n-micro replace-values --search "Hello\\\\d+" --replace "Hi" --useRegex
Example 3: Using regex capturing groups
Use capturing groups to dynamically insert part of the matched string into the replacement. For example, replace "Hello [name]" with "Hi [name]" while keeping the name intact:
i18n-micro replace-values --search "Hello (\\\\w+)" --replace "Hi $1" --useRegex
In this case, $1
refers to the first capturing group, which matches the [name]
part after "Hello". The replacement will keep the name from the original string.
How it works:
$1
, $2
, etc.Logging: For each replacement, the command logs details including:
This allows you to track exactly where and what changes were made during the replacement operation, providing a clear history of modifications across your translation files.
Extracting translations:
i18n-micro extract
Translating missing keys using Google Translate:
i18n-micro translate --service google --token YOUR_GOOGLE_API_KEY
Translating all keys, replacing existing translations:
i18n-micro translate --service deepl --token YOUR_DEEPL_API_KEY --replace
Validating translation files:
i18n-micro validate
Cleaning unused translation keys:
i18n-micro clean
Synchronizing translation files:
i18n-micro sync
nuxt-i18n-micro-cli
relies on your Nuxt.js i18n configuration in nuxt.config.js
. Ensure you have the nuxt-i18n
module installed and configured.
export default {\n modules: ['@nuxtjs/i18n'],\n i18n: {\n locales: [\n { code: 'en', iso: 'en-US' },\n { code: 'fr', iso: 'fr-FR' },\n { code: 'es', iso: 'es-ES' },\n // Add other locales as needed\n ],\n defaultLocale: 'en',\n vueI18n: {\n fallbackLocale: 'en',\n },\n // Specify the directory where your translation files are stored\n translationDir: 'locales',\n },\n};
Ensure that the translationDir
matches the directory used by nuxt-i18n-micro-cli
(default is locales
).
Ensure translation keys are consistent and descriptive to avoid confusion and duplication.
Use the clean
command regularly to remove unused translation keys and keep your translation files clean.
Integrate nuxt-i18n-micro-cli
commands into your development workflow or CI/CD pipeline to automate extraction, translation, validation, and synchronization of translation files.
When using translation services that require API keys, ensure your keys are kept secure and not committed to version control systems. Consider using environment variables or secure key management solutions.
If you encounter issues or have suggestions for improvements, feel free to contribute to the project or open an issue on the project's repository.
By following this guide, you'll be able to effectively manage translations in your Nuxt.js project using nuxt-i18n-micro-cli
, streamlining your internationalization efforts and ensuring a smooth experience for users in different locales.
nuxt-i18n-micro-cli
is a command-line tool designed to streamline the localization and internationalization process in Nuxt.js projects using the nuxt-i18n
module. It provides utilities to extract translation keys from your codebase, manage translation files, synchronize translations across locales, and automate the translation process using external translation services.
This guide will walk you through installing, configuring, and using nuxt-i18n-micro-cli
to effectively manage your project's translations. Package on npmjs.com.
Install nuxt-i18n-micro-cli
globally using npm:
npm install -g nuxt-i18n-micro-cli
This will make the i18n-micro
command available globally on your system.
After installing, you can run i18n-micro
commands in your Nuxt.js project directory.
Ensure that your project is set up with nuxt-i18n
and has the necessary configuration in nuxt.config.js
.
--cwd
: Specify the current working directory (defaults to .
).--logLevel
: Set the log level (silent
, info
, verbose
).--translationDir
: Directory containing JSON translation files (default: locales
).text-to-i18n
Command Version introduced: v1.1.0
Description: The text-to-i18n
command automatically scans your codebase for hardcoded text strings and replaces them with i18n translation references. It extracts text from Vue templates, JavaScript, and TypeScript files, generating translation keys and updating your translation files.
Usage:
i18n-micro text-to-i18n [options]
Options:
--translationFile
: Path to the JSON file containing translations (default: locales/en.json
).--context
: Context prefix for translation keys. Helps organize translations by feature or section.--dryRun
: Show changes without modifying files (default: false
).--verbose
: Show detailed processing information (default: false
).--path
: Path to a specific file to process (e.g., ./pages/test-page.vue
). When provided, only the specified file is processed.Example:
i18n-micro text-to-i18n --translationFile locales/en.json --context auth
How it works:
pages
, components
, and plugins
.vue
, .js
, and .ts
Example Transformations:
Before:
<template>\n <div>\n <h1>Welcome to our site</h1>\n <p>Please sign in to continue</p>\n </div>\n</template>
After:
<template>\n <div>\n <h1>{{ $t('pages.home.welcome_to_our_site') }}</h1>\n <p>{{ $t('pages.home.please_sign_in') }}</p>\n </div>\n</template>
Best Practices:
Run in Dry Mode First:
i18n-micro text-to-i18n --dryRun
This shows what changes would be made without modifying files.
Use Context for Organization:
i18n-micro text-to-i18n --context auth
Prefixes translation keys with auth.
for better organization.
Review Changes:
Notes:
stats
Command Description: The stats
command is used to display translation statistics for each locale in your Nuxt.js project. It helps you understand the progress of your translations by showing how many keys are translated compared to the total number of keys available.
Usage:
i18n-micro stats [options]
Options:
--full
: Display combined translations statistics only (default: false
).Example:
i18n-micro stats --full
translate
Command Description: The translate
command automatically translates missing keys using external translation services. This command simplifies the translation process by leveraging APIs from services like Google Translate, DeepL, and others to fill in missing translations.
Usage:
i18n-micro translate [options]
Options:
--service
: Translation service to use (e.g., google
, deepl
, yandex
). If not specified, the command will prompt you to select one.--token
: API key corresponding to the chosen translation service. If not provided, you will be prompted to enter it.--options
: Additional options for the translation service, provided as key:value pairs, separated by commas (e.g., model:gpt-3.5-turbo,max_tokens:1000
).--replace
: Translate all keys, replacing existing translations (default: false
).Example:
i18n-micro translate --service deepl --token YOUR_DEEPL_API_KEY
The translate
command supports multiple translation services. Some of the supported services are:
google
)deepl
)yandex
)openai
)azure
)ibm
)baidu
)libretranslate
)mymemory
)lingvatranslate
)papago
)tencent
)systran
)yandexcloud
)modernmt
)lilt
)unbabel
)reverso
)Some services require specific configurations or API keys. When using the translate
command, you can specify the service and provide the required --token
(API key) and additional --options
if needed.
For example:
i18n-micro translate --service openai --token YOUR_OPENAI_API_KEY --options openaiModel:gpt-3.5-turbo,max_tokens:1000
extract
Command Description: Extracts translation keys from your codebase and organizes them by scope.
Usage:
i18n-micro extract [options]
Options:
--prod, -p
: Run in production mode.Example:
i18n-micro extract
sync
Command Description: Synchronizes translation files across locales, ensuring all locales have the same keys.
Usage:
i18n-micro sync [options]
Example:
i18n-micro sync
validate
Command Description: Validates translation files for missing or extra keys compared to the reference locale.
Usage:
i18n-micro validate [options]
Example:
i18n-micro validate
clean
Command Description: Removes unused translation keys from translation files.
Usage:
i18n-micro clean [options]
Example:
i18n-micro clean
import
Command Description: Converts PO files back to JSON format and saves them in the translation directory.
Usage:
i18n-micro import [options]
Options:
--potsDir
: Directory containing PO files (default: pots
).Example:
i18n-micro import --potsDir pots
export
Command Description: Exports translations to PO files for external translation management.
Usage:
i18n-micro export [options]
Options:
--potsDir
: Directory to save PO files (default: pots
).Example:
i18n-micro export --potsDir pots
export-csv
Command Description: The export-csv
command exports translation keys and values from JSON files, including their file paths, into a CSV format. This command is useful for teams who prefer working with translation data in spreadsheet software.
Usage:
i18n-micro export-csv [options]
Options:
--csvDir
: Directory where the exported CSV files will be saved.--delimiter
: Specify a delimiter for the CSV file (default: ,
).Example:
i18n-micro export-csv --csvDir csv_files
import-csv
Command Description: The import-csv
command imports translation data from CSV files, updating the corresponding JSON files. This is useful for applying bulk translation updates from spreadsheets.
Usage:
i18n-micro import-csv [options]
Options:
--csvDir
: Directory containing the CSV files to be imported.--delimiter
: Specify a delimiter used in the CSV file (default: ,
).Example:
i18n-micro import-csv --csvDir csv_files
diff
Command Description: Compares translation files between the default locale and other locales within the same directory (including subdirectories). The command identifies missing keys and their values in the default locale compared to other locales, making it easier to track translation progress or discrepancies.
Usage:
i18n-micro diff [options]
Example:
i18n-micro diff
check-duplicates
Command Description: The check-duplicates
command checks for duplicate translation values within each locale across all translation files, including both global and page-specific translations. It ensures that different keys within the same language do not share identical translation values, helping maintain clarity and consistency in your translations.
Usage:
i18n-micro check-duplicates [options]
Example:
i18n-micro check-duplicates
How it works:
This command helps ensure that translation keys maintain unique values, preventing accidental repetition within the same locale.
replace-values
Command Description: The replace-values
command allows you to perform bulk replacements of translation values across all locales. It supports both simple text replacements and advanced replacements using regular expressions (regex). You can also use capturing groups in regex patterns and reference them in the replacement string, making it ideal for more complex replacement scenarios.
Usage:
i18n-micro replace-values [options]
Options:
--search
: The text or regex pattern to search for in translations. This is a required option.--replace
: The replacement text to be used for the found translations. This is a required option.--useRegex
: Enable search using a regular expression pattern (default: false
).Example 1: Simple replacement
Replace the string "Hello" with "Hi" across all locales:
i18n-micro replace-values --search "Hello" --replace "Hi"
Example 2: Regex replacement
Enable regex search and replace any string starting with "Hello" followed by numbers (e.g., "Hello123") with "Hi" across all locales:
i18n-micro replace-values --search "Hello\\\\d+" --replace "Hi" --useRegex
Example 3: Using regex capturing groups
Use capturing groups to dynamically insert part of the matched string into the replacement. For example, replace "Hello [name]" with "Hi [name]" while keeping the name intact:
i18n-micro replace-values --search "Hello (\\\\w+)" --replace "Hi $1" --useRegex
In this case, $1
refers to the first capturing group, which matches the [name]
part after "Hello". The replacement will keep the name from the original string.
How it works:
$1
, $2
, etc.Logging: For each replacement, the command logs details including:
This allows you to track exactly where and what changes were made during the replacement operation, providing a clear history of modifications across your translation files.
Extracting translations:
i18n-micro extract
Translating missing keys using Google Translate:
i18n-micro translate --service google --token YOUR_GOOGLE_API_KEY
Translating all keys, replacing existing translations:
i18n-micro translate --service deepl --token YOUR_DEEPL_API_KEY --replace
Validating translation files:
i18n-micro validate
Cleaning unused translation keys:
i18n-micro clean
Synchronizing translation files:
i18n-micro sync
nuxt-i18n-micro-cli
relies on your Nuxt.js i18n configuration in nuxt.config.js
. Ensure you have the nuxt-i18n
module installed and configured.
export default {\n modules: ['@nuxtjs/i18n'],\n i18n: {\n locales: [\n { code: 'en', iso: 'en-US' },\n { code: 'fr', iso: 'fr-FR' },\n { code: 'es', iso: 'es-ES' },\n // Add other locales as needed\n ],\n defaultLocale: 'en',\n vueI18n: {\n fallbackLocale: 'en',\n },\n // Specify the directory where your translation files are stored\n translationDir: 'locales',\n },\n};
Ensure that the translationDir
matches the directory used by nuxt-i18n-micro-cli
(default is locales
).
Ensure translation keys are consistent and descriptive to avoid confusion and duplication.
Use the clean
command regularly to remove unused translation keys and keep your translation files clean.
Integrate nuxt-i18n-micro-cli
commands into your development workflow or CI/CD pipeline to automate extraction, translation, validation, and synchronization of translation files.
When using translation services that require API keys, ensure your keys are kept secure and not committed to version control systems. Consider using environment variables or secure key management solutions.
If you encounter issues or have suggestions for improvements, feel free to contribute to the project or open an issue on the project's repository.
By following this guide, you'll be able to effectively manage translations in your Nuxt.js project using nuxt-i18n-micro-cli
, streamlining your internationalization efforts and ensuring a smooth experience for users in different locales.
Thank you for your interest in contributing to Nuxt I18n Micro
! We welcome contributions from the community, whether it's bug fixes, new features, or improvements to the documentation. This guide outlines the steps to help you get started and ensures that your contributions can be easily integrated into the project.
Before making changes, it's a good idea to familiarize yourself with the project's architecture and codebase. Read through the existing documentation and take a look at open issues and pull requests to understand ongoing work and challenges.
Clone the forked repository to your local machine:
git clone https://github.com/<your-username>/nuxt-i18n-micro.git
+cd nuxt-i18n-micro
Replace <your-username>
with your GitHub username.
Create a new branch for your work:
git checkout -b feature/your-feature-name
Use descriptive branch names, such as bugfix/fix-translation-error
or feature/add-new-locale-support
.
Before you begin, ensure that you have the following installed on your machine:
First, you need to clone the nuxt-i18n-micro
repository to your local machine.
git clone https://github.com/s00d/nuxt-i18n-micro.git
+cd nuxt-i18n-micro
Next, install the project dependencies using pnpm.
pnpm install
+pnpm --filter "./packages/**" run build
+pnpm run prepack && cd playground && pnpm run prepare && cd ..
To start the development server and work on the module, run the following command:
pnpm run dev
This command will start the Nuxt development server using the playground
directory as the testing environment. You can view the app in your browser by navigating to http://localhost:3000
.
To build the module, use the following command:
pnpm run prepack
This command prepares the module by building the necessary files, stubbing certain components, and ensuring everything is ready for packaging.
To ensure your code adheres to the project's coding standards, run the linter:
pnpm run lint
If there are any issues, you can attempt to automatically fix them using:
pnpm run lint:fix
To run the test suite, use the following command:
pnpm run test:workspaces
+pnpm run test
This will run all the Playwright tests to ensure everything is functioning as expected.
For TypeScript type checking, run:
pnpm run typecheck
+pnpm run test:types
+pnpm run test
This checks the type definitions to ensure there are no type errors.
To build and preview the documentation locally, use the following commands:
pnpm run docs:build
+pnpm run docs:serve
This will build the documentation and serve it locally, allowing you to view it in your browser.
If you want to test your changes in a sample Nuxt application, the playground
directory serves as a sandbox environment. Run the following command to start the playground:
pnpm run dev:build
You can access the playground app at http://localhost:3000
.
pnpm run dev
: Start the development server using the playground.pnpm run prepack
: Build the module and prepare it for publishing.pnpm --filter "./packages/**" run build
: Build the packages.pnpm run lint
: Run the linter to check for code quality issues.pnpm run lint:fix
: Automatically fix linter issues.pnpm run test
: Run the test suite.pnpm run test:workspaces
: Run the test suite for packages.pnpm run typecheck
: Check TypeScript types.pnpm run docs:dev
: Start the documentation site in development mode.pnpm run docs:build
: Build the documentation site.pnpm run docs:serve
: Serve the built documentation site locally.pnpm run dev:build
: Build the playground environment.Before committing your changes, ensure that your code adheres to the project's coding standards by running the linter:
pnpm run lint
Fix any linting errors before proceeding.
Make sure your changes work and do not break any existing functionality:
pnpm run test:workspaces
+pnpm run test
To ensure consistency across the project, we use a standardized commit message format. Please follow this format when making commits:
Each commit message should be structured as follows:
<type>(<scope>): <short description>
fix(router): resolve issue with locale switching
feat(seo): add automatic og:locale meta tag generation
docs(contribution): update contribution guide with commit message format
For more details, refer to the Conventional Commits Specification.
Push your changes to your fork on GitHub:
git push origin feature/your-feature-name
main
branch of the original repository (s00d/nuxt-i18n-micro
).Once your pull request is submitted, a maintainer will review your changes. Be prepared to make adjustments based on feedback. Once approved, your PR will be merged into the main branch.
Nuxt I18n Micro
better.Thank you for your interest in contributing to Nuxt I18n Micro
! We welcome contributions from the community, whether it's bug fixes, new features, or improvements to the documentation. This guide outlines the steps to help you get started and ensures that your contributions can be easily integrated into the project.
Before making changes, it's a good idea to familiarize yourself with the project's architecture and codebase. Read through the existing documentation and take a look at open issues and pull requests to understand ongoing work and challenges.
Clone the forked repository to your local machine:
git clone https://github.com/<your-username>/nuxt-i18n-micro.git
+cd nuxt-i18n-micro
Replace <your-username>
with your GitHub username.
Create a new branch for your work:
git checkout -b feature/your-feature-name
Use descriptive branch names, such as bugfix/fix-translation-error
or feature/add-new-locale-support
.
Before you begin, ensure that you have the following installed on your machine:
First, you need to clone the nuxt-i18n-micro
repository to your local machine.
git clone https://github.com/s00d/nuxt-i18n-micro.git
+cd nuxt-i18n-micro
Next, install the project dependencies using pnpm.
pnpm install
+pnpm --filter "./packages/**" run build
+pnpm run prepack && cd playground && pnpm run prepare && cd ..
To start the development server and work on the module, run the following command:
pnpm run dev
This command will start the Nuxt development server using the playground
directory as the testing environment. You can view the app in your browser by navigating to http://localhost:3000
.
To build the module, use the following command:
pnpm run prepack
This command prepares the module by building the necessary files, stubbing certain components, and ensuring everything is ready for packaging.
To ensure your code adheres to the project's coding standards, run the linter:
pnpm run lint
If there are any issues, you can attempt to automatically fix them using:
pnpm run lint:fix
To run the test suite, use the following command:
pnpm run test:workspaces
+pnpm run test
This will run all the Playwright tests to ensure everything is functioning as expected.
For TypeScript type checking, run:
pnpm run typecheck
+pnpm run test:types
+pnpm run test
This checks the type definitions to ensure there are no type errors.
To build and preview the documentation locally, use the following commands:
pnpm run docs:build
+pnpm run docs:serve
This will build the documentation and serve it locally, allowing you to view it in your browser.
If you want to test your changes in a sample Nuxt application, the playground
directory serves as a sandbox environment. Run the following command to start the playground:
pnpm run dev:build
You can access the playground app at http://localhost:3000
.
pnpm run dev
: Start the development server using the playground.pnpm run prepack
: Build the module and prepare it for publishing.pnpm --filter "./packages/**" run build
: Build the packages.pnpm run lint
: Run the linter to check for code quality issues.pnpm run lint:fix
: Automatically fix linter issues.pnpm run test
: Run the test suite.pnpm run test:workspaces
: Run the test suite for packages.pnpm run typecheck
: Check TypeScript types.pnpm run docs:dev
: Start the documentation site in development mode.pnpm run docs:build
: Build the documentation site.pnpm run docs:serve
: Serve the built documentation site locally.pnpm run dev:build
: Build the playground environment.Before committing your changes, ensure that your code adheres to the project's coding standards by running the linter:
pnpm run lint
Fix any linting errors before proceeding.
Make sure your changes work and do not break any existing functionality:
pnpm run test:workspaces
+pnpm run test
To ensure consistency across the project, we use a standardized commit message format. Please follow this format when making commits:
Each commit message should be structured as follows:
<type>(<scope>): <short description>
fix(router): resolve issue with locale switching
feat(seo): add automatic og:locale meta tag generation
docs(contribution): update contribution guide with commit message format
For more details, refer to the Conventional Commits Specification.
Push your changes to your fork on GitHub:
git push origin feature/your-feature-name
main
branch of the original repository (s00d/nuxt-i18n-micro
).Once your pull request is submitted, a maintainer will review your changes. Be prepared to make adjustments based on feedback. Once approved, your PR will be merged into the main branch.
Nuxt I18n Micro
better.Integrating Crowdin into your project streamlines the localization and translation process, making it easier to manage translations across multiple languages and platforms. This guide provides a step-by-step walkthrough on setting up Crowdin with your project, including configuration, uploading sources, and downloading translations.
To get started with Crowdin, you'll need to install the Crowdin CLI globally on your machine and initialize it within your project directory.
First, install the Crowdin CLI globally using npm:
npm install -g @crowdin/cli
Initialize Crowdin in your project by running:
crowdin init
This command will guide you through the setup process, including setting your project ID, API token, and other configuration details.
crowdin.yml
) The Crowdin configuration file (crowdin.yml
) defines how your source files are mapped and where translations should be placed. Below is an example configuration:
"project_id": "YOUR_PROJECT_ID"
+"api_token": "YOUR_API_TOKEN"
+"base_path": "./locales"
+"base_url": "https://api.crowdin.com"
+"preserve_hierarchy": true
+
+files: [
+ {
+ "source": "/en.json",
+ "translation": "/%two_letters_code%.json",
+ },
+ {
+ "source": "/pages/**/en.json",
+ "translation": "/pages/**/%two_letters_code%.json",
+ }
+]
project_id
: Your Crowdin project ID. This identifies the project within Crowdin where translations are managed.api_token
: The API token used for authentication. Ensure this token has the correct permissions to upload and download translations.base_path
: Specifies the base directory for source files. In this example, translations are stored in the ./locales
directory.base_url
: The base URL for the Crowdin API.preserve_hierarchy
: When set to true
, Crowdin will maintain the folder structure of your source files in the project.The files
section maps your source files to the paths where translations will be stored. For example:
%two_letters_code%
are used to dynamically set the language code in the file paths.Once your Crowdin configuration is set up, you can upload your source files using the following command:
crowdin upload sources
This command uploads all specified source files in your configuration to Crowdin, making them available for translation.
After translations are completed or updated in Crowdin, you can download them to your project using:
crowdin download
This command fetches the latest translations from Crowdin and saves them according to the paths specified in your configuration file.
Ensure translation keys are consistent across all files to avoid confusion and duplication.
Periodically review and clean up unused translation keys to keep your files organized and manageable.
Integrate the Crowdin CLI commands into your CI/CD pipeline to automate the upload of source files and download of translations, ensuring your translations are always up to date.
By following this guide, you’ll be able to seamlessly integrate Crowdin into your project, ensuring an efficient and organized approach to managing your internationalization efforts.
`,37)]))}const g=a(t,[["render",o]]);export{u as __pageData,g as default}; diff --git a/assets/guide_crowdin.md.DgJWT6GK.lean.js b/assets/guide_crowdin.md.DgJWT6GK.lean.js new file mode 100644 index 00000000..6c29ee2f --- /dev/null +++ b/assets/guide_crowdin.md.DgJWT6GK.lean.js @@ -0,0 +1,16 @@ +import{_ as a,c as s,a2 as n,o as e}from"./chunks/framework.Gfs4HC1t.js";const u=JSON.parse('{"title":"🌐 Crowdin Integration Guide","description":"","frontmatter":{"outline":"deep"},"headers":[],"relativePath":"guide/crowdin.md","filePath":"guide/crowdin.md","lastUpdated":1726410447000}'),t={name:"guide/crowdin.md"};function o(l,i,r,d,h,p){return e(),s("div",null,i[0]||(i[0]=[n(`Integrating Crowdin into your project streamlines the localization and translation process, making it easier to manage translations across multiple languages and platforms. This guide provides a step-by-step walkthrough on setting up Crowdin with your project, including configuration, uploading sources, and downloading translations.
To get started with Crowdin, you'll need to install the Crowdin CLI globally on your machine and initialize it within your project directory.
First, install the Crowdin CLI globally using npm:
npm install -g @crowdin/cli
Initialize Crowdin in your project by running:
crowdin init
This command will guide you through the setup process, including setting your project ID, API token, and other configuration details.
crowdin.yml
) The Crowdin configuration file (crowdin.yml
) defines how your source files are mapped and where translations should be placed. Below is an example configuration:
"project_id": "YOUR_PROJECT_ID"
+"api_token": "YOUR_API_TOKEN"
+"base_path": "./locales"
+"base_url": "https://api.crowdin.com"
+"preserve_hierarchy": true
+
+files: [
+ {
+ "source": "/en.json",
+ "translation": "/%two_letters_code%.json",
+ },
+ {
+ "source": "/pages/**/en.json",
+ "translation": "/pages/**/%two_letters_code%.json",
+ }
+]
project_id
: Your Crowdin project ID. This identifies the project within Crowdin where translations are managed.api_token
: The API token used for authentication. Ensure this token has the correct permissions to upload and download translations.base_path
: Specifies the base directory for source files. In this example, translations are stored in the ./locales
directory.base_url
: The base URL for the Crowdin API.preserve_hierarchy
: When set to true
, Crowdin will maintain the folder structure of your source files in the project.The files
section maps your source files to the paths where translations will be stored. For example:
%two_letters_code%
are used to dynamically set the language code in the file paths.Once your Crowdin configuration is set up, you can upload your source files using the following command:
crowdin upload sources
This command uploads all specified source files in your configuration to Crowdin, making them available for translation.
After translations are completed or updated in Crowdin, you can download them to your project using:
crowdin download
This command fetches the latest translations from Crowdin and saves them according to the paths specified in your configuration file.
Ensure translation keys are consistent across all files to avoid confusion and duplication.
Periodically review and clean up unused translation keys to keep your files organized and manageable.
Integrate the Crowdin CLI commands into your CI/CD pipeline to automate the upload of source files and download of translations, ensuring your translations are always up to date.
By following this guide, you’ll be able to seamlessly integrate Crowdin into your project, ensuring an efficient and organized approach to managing your internationalization efforts.
`,37)]))}const g=a(t,[["render",o]]);export{u as __pageData,g as default}; diff --git a/assets/guide_custom-locale-routes.md.65G7AEaG.js b/assets/guide_custom-locale-routes.md.65G7AEaG.js new file mode 100644 index 00000000..6677d39a --- /dev/null +++ b/assets/guide_custom-locale-routes.md.65G7AEaG.js @@ -0,0 +1,35 @@ +import{_ as i,c as a,a2 as e,o as t}from"./chunks/framework.Gfs4HC1t.js";const d=JSON.parse('{"title":"🔗 Custom Localized Routes with localeRoutes in Nuxt I18n Micro","description":"","frontmatter":{"outline":"deep"},"headers":[],"relativePath":"guide/custom-locale-routes.md","filePath":"guide/custom-locale-routes.md","lastUpdated":1725088182000}'),n={name:"guide/custom-locale-routes.md"};function l(o,s,h,p,r,k){return t(),a("div",null,s[0]||(s[0]=[e(`localeRoutes
in Nuxt I18n Micro
localeRoutes
The localeRoutes
feature in Nuxt I18n Micro
allows you to define custom routes for specific locales, offering flexibility and control over the routing structure of your application. This feature is particularly useful when certain locales require different URL structures, tailored paths, or need to follow specific regional or linguistic conventions.
localeRoutes
The primary use case for localeRoutes
is to provide distinct routes for different locales, enhancing the user experience by ensuring URLs are intuitive and relevant to the target audience. For example, you might have different paths for English and Russian versions of a page, where the Russian locale follows a localized URL format.
localeRoutes
in $defineI18nRoute
Here’s an example of how you might define custom routes for specific locales using localeRoutes
in your $defineI18nRoute
function:
$defineI18nRoute({
+ localeRoutes: {
+ ru: '/localesubpage', // Custom route path for the Russian locale
+ de: '/lokaleseite', // Custom route path for the German locale
+ },
+})
localeRoutes
Work localeRoutes
, all locales use a common route structure defined by the primary path.localeRoutes
, specific locales can have their own routes, overriding the default path with locale-specific routes defined in the configuration.localeRoutes
localeRoutes
in a Page Here’s a simple Vue component demonstrating the use of $defineI18nRoute
with localeRoutes
:
<template>
+ <div>
+ <!-- Display greeting message based on the current locale -->
+ <p>{{ $t('greeting') }}</p>
+
+ <!-- Navigation links -->
+ <div>
+ <NuxtLink :to="$localeRoute({ name: 'index' })">
+ Go to Index
+ </NuxtLink>
+ |
+ <NuxtLink :to="$localeRoute({ name: 'about' })">
+ Go to About Page
+ </NuxtLink>
+ </div>
+ </div>
+</template>
+
+<script setup>
+import { useNuxtApp } from '#imports'
+
+const { $getLocale, $switchLocale, $getLocales, $localeRoute, $t, $defineI18nRoute } = useNuxtApp()
+
+// Define translations and custom routes for specific locales
+$defineI18nRoute({
+ localeRoutes: {
+ ru: '/localesubpage', // Custom route path for Russian locale
+ },
+})
+</script>
localeRoutes
in Different Contexts localeRoutes
localeRoutes
primarily where the URL structure significantly impacts the user experience or SEO. Avoid overuse for minor differences.localeRoutes
, especially in modular applications, to ensure team members understand the routing logic.localeRoutes
in Nuxt I18n Micro
localeRoutes
The localeRoutes
feature in Nuxt I18n Micro
allows you to define custom routes for specific locales, offering flexibility and control over the routing structure of your application. This feature is particularly useful when certain locales require different URL structures, tailored paths, or need to follow specific regional or linguistic conventions.
localeRoutes
The primary use case for localeRoutes
is to provide distinct routes for different locales, enhancing the user experience by ensuring URLs are intuitive and relevant to the target audience. For example, you might have different paths for English and Russian versions of a page, where the Russian locale follows a localized URL format.
localeRoutes
in $defineI18nRoute
Here’s an example of how you might define custom routes for specific locales using localeRoutes
in your $defineI18nRoute
function:
$defineI18nRoute({
+ localeRoutes: {
+ ru: '/localesubpage', // Custom route path for the Russian locale
+ de: '/lokaleseite', // Custom route path for the German locale
+ },
+})
localeRoutes
Work localeRoutes
, all locales use a common route structure defined by the primary path.localeRoutes
, specific locales can have their own routes, overriding the default path with locale-specific routes defined in the configuration.localeRoutes
localeRoutes
in a Page Here’s a simple Vue component demonstrating the use of $defineI18nRoute
with localeRoutes
:
<template>
+ <div>
+ <!-- Display greeting message based on the current locale -->
+ <p>{{ $t('greeting') }}</p>
+
+ <!-- Navigation links -->
+ <div>
+ <NuxtLink :to="$localeRoute({ name: 'index' })">
+ Go to Index
+ </NuxtLink>
+ |
+ <NuxtLink :to="$localeRoute({ name: 'about' })">
+ Go to About Page
+ </NuxtLink>
+ </div>
+ </div>
+</template>
+
+<script setup>
+import { useNuxtApp } from '#imports'
+
+const { $getLocale, $switchLocale, $getLocales, $localeRoute, $t, $defineI18nRoute } = useNuxtApp()
+
+// Define translations and custom routes for specific locales
+$defineI18nRoute({
+ localeRoutes: {
+ ru: '/localesubpage', // Custom route path for Russian locale
+ },
+})
+</script>
localeRoutes
in Different Contexts localeRoutes
localeRoutes
primarily where the URL structure significantly impacts the user experience or SEO. Avoid overuse for minor differences.localeRoutes
, especially in modular applications, to ensure team members understand the routing logic.nuxt-i18n-micro
DevTools is a powerful development assistant seamlessly integrated into the nuxt-i18n-micro
module. It provides an intuitive interface for managing localization and translation tasks, making your workflow faster and more efficient. Designed for developers who value convenience, Nuxt DevTools bridges the gap between coding and runtime management.
nuxt-i18n-micro
Effortlessly browse, select, and manage locales in your application. Whether you’re working with a single language or multiple, DevTools provides a centralized hub for handling all localization settings.
Edit translation files directly through an integrated JSON editor. This eliminates the need for external tools, allowing real-time updates and changes without interrupting your workflow.
Simplify the process of managing translation files:
View changes immediately within the development environment. This feature ensures translations and configurations are accurate before going live.
DevTools works natively with nuxt-i18n-micro
, enhancing its capabilities without requiring additional setup. It adapts to your localization needs while maintaining Nuxt's modular and flexible structure.
Nuxt DevTools is an indispensable addition for projects requiring localization. It helps developers by:
With Nuxt DevTools integrated into nuxt-i18n-micro
, managing multilingual applications becomes straightforward and efficient. Whether you're fine-tuning translations or adding new locales, DevTools equips you with the tools needed to deliver polished, user-friendly experiences.
nuxt-i18n-micro
DevTools is a powerful development assistant seamlessly integrated into the nuxt-i18n-micro
module. It provides an intuitive interface for managing localization and translation tasks, making your workflow faster and more efficient. Designed for developers who value convenience, Nuxt DevTools bridges the gap between coding and runtime management.
nuxt-i18n-micro
Effortlessly browse, select, and manage locales in your application. Whether you’re working with a single language or multiple, DevTools provides a centralized hub for handling all localization settings.
Edit translation files directly through an integrated JSON editor. This eliminates the need for external tools, allowing real-time updates and changes without interrupting your workflow.
Simplify the process of managing translation files:
View changes immediately within the development environment. This feature ensures translations and configurations are accurate before going live.
DevTools works natively with nuxt-i18n-micro
, enhancing its capabilities without requiring additional setup. It adapts to your localization needs while maintaining Nuxt's modular and flexible structure.
Nuxt DevTools is an indispensable addition for projects requiring localization. It helps developers by:
With Nuxt DevTools integrated into nuxt-i18n-micro
, managing multilingual applications becomes straightforward and efficient. Whether you're fine-tuning translations or adding new locales, DevTools equips you with the tools needed to deliver polished, user-friendly experiences.
When using Nuxt I18n Micro
, certain routes might not load as expected, especially if the router doesn't automatically assign a name to a route in subfolders.
Solution: To address this, manually define the route name for the page by adding the following to the corresponding Vue file:
definePageMeta({ name: 'pageName' })
This ensures the route is properly registered, enabling seamless navigation within the application.
assets/_locales/
folder added to the server folder? During deployment, especially on platforms like Netlify, the build process might differ from local development. This can lead to issues where certain files or folders are missing during server-side rendering (SSR).
Explanation:
$fetch
in SSR, causing middleware to miss localization files.Nuxt I18n Micro
inspired by vue-i18n
? What about modifiers? While Nuxt I18n Micro
serves as a performance alternative to nuxt-i18n
, it’s built independently of vue-i18n
. While some method names and parameters may be similar, the underlying functionality differs significantly.
Modifiers: The maintainer initially considered modifiers, but concluded that components like <i18n-t>
and <i18n-link>
effectively address those needs.
For example:
<template>
+ <i18n-t keypath="feedback.text">
+ <template #link>
+ <nuxt-link :to="{ name: 'index' }">
+ <i18n-t keypath="feedback.link" />
+ </nuxt-link>
+ </template>
+ </i18n-t>
+</template>
This approach is flexible, so releasing modifiers is currently unnecessary. However, modifiers may be added in future releases if there is demand.
NuxtLink
or i18nLink
directly in translation strings? Yes, Nuxt I18n Micro
allows the use of NuxtLink
or i18nLink
within translations through the <i18n-t>
component, which is especially helpful for handling grammar and RTL language requirements without splitting translation strings.
Example:
Translation file:
{
+ "example": "Share your {link} with friends",
+ "link_text": "translation link"
+}
Vue template:
<template>
+ <i18n-t keypath="example">
+ <template #link>
+ <nuxt-link :to="{ name: 'referral' }">
+ <i18n-t keypath="link_text" />
+ </nuxt-link>
+ </template>
+ </i18n-t>
+</template>
This allows dynamic links within translations while preserving proper localization structure.
$fetch
limitations on SSR On serverless platforms like Vercel, $fetch
can only fetch static files from the CDN and not from the internal Nitro server. This means static translation files may not be directly accessible unless the correct base URL is set.
apiBaseUrl
If translations are hosted externally, specify the full URL (e.g., https://example.com/_locales
) for $fetch
to access the translations correctly during SSR.
Example:
{
+ // ...
+ apiBaseUrl: 'https://example.com/_locales'
+ // ...
+}
$t
or other i18n composables not work in Nuxt plugins? Nuxt I18n composables ($t
, $getLocale
, $localePath
, etc.) may not work as expected within Nuxt plugins or utility functions, resulting in runtime errors.
Cause and Solution: Nuxt composables require specific contexts (e.g., Nuxt hooks or Vue setup functions) to access the Nuxt instance. If used outside of these contexts (e.g., in utility functions or plugins), the following error might appear in the console:
[nuxt] A composable that requires access to the Nuxt instance was called outside of a plugin, Nuxt hook, Nuxt middleware, or Vue setup function. This is probably not a Nuxt bug. Find out more at https://nuxt.com/docs/guide/concepts/auto-imports#vue-and-nuxt-composables
Solution 1: Use runWithContext
To call i18n composables after an asynchronous operation, use runWithContext
to preserve the necessary context.
Example:
await nuxtApp.runWithContext(() => $t('test_key'))
Solution 2: Retrieve Value First Alternatively, retrieve the translation value first, then pass it to a utility function.
Example:
const val = nuxtApp.$t('common.errors.unknown.title')
+showError({
+ title: val
+})
Solution 3: Pass Translation Keys in Services In services or utility functions, pass the translation keys instead of using $t
directly. Then, fetch the translation in the component.
Example:
showError({
+ title: 'common.errors.unknown.title',
+ message: 'common.errors.unknown.message',
+ i18n: true
+})
These solutions help maintain context and reduce errors, allowing for flexibility in handling translations across the application.
`,50)]))}const E=i(n,[["render",l]]);export{c as __pageData,E as default}; diff --git a/assets/guide_faq.md.dIiCo_1b.lean.js b/assets/guide_faq.md.dIiCo_1b.lean.js new file mode 100644 index 00000000..0c21249b --- /dev/null +++ b/assets/guide_faq.md.dIiCo_1b.lean.js @@ -0,0 +1,31 @@ +import{_ as i,c as a,a2 as t,o as e}from"./chunks/framework.Gfs4HC1t.js";const c=JSON.parse('{"title":"FAQ: Common Issues & Solutions","description":"","frontmatter":{"outline":"deep"},"headers":[],"relativePath":"guide/faq.md","filePath":"guide/faq.md","lastUpdated":1734691342000}'),n={name:"guide/faq.md"};function l(h,s,p,o,r,k){return e(),a("div",null,s[0]||(s[0]=[t(`When using Nuxt I18n Micro
, certain routes might not load as expected, especially if the router doesn't automatically assign a name to a route in subfolders.
Solution: To address this, manually define the route name for the page by adding the following to the corresponding Vue file:
definePageMeta({ name: 'pageName' })
This ensures the route is properly registered, enabling seamless navigation within the application.
assets/_locales/
folder added to the server folder? During deployment, especially on platforms like Netlify, the build process might differ from local development. This can lead to issues where certain files or folders are missing during server-side rendering (SSR).
Explanation:
$fetch
in SSR, causing middleware to miss localization files.Nuxt I18n Micro
inspired by vue-i18n
? What about modifiers? While Nuxt I18n Micro
serves as a performance alternative to nuxt-i18n
, it’s built independently of vue-i18n
. While some method names and parameters may be similar, the underlying functionality differs significantly.
Modifiers: The maintainer initially considered modifiers, but concluded that components like <i18n-t>
and <i18n-link>
effectively address those needs.
For example:
<template>
+ <i18n-t keypath="feedback.text">
+ <template #link>
+ <nuxt-link :to="{ name: 'index' }">
+ <i18n-t keypath="feedback.link" />
+ </nuxt-link>
+ </template>
+ </i18n-t>
+</template>
This approach is flexible, so releasing modifiers is currently unnecessary. However, modifiers may be added in future releases if there is demand.
NuxtLink
or i18nLink
directly in translation strings? Yes, Nuxt I18n Micro
allows the use of NuxtLink
or i18nLink
within translations through the <i18n-t>
component, which is especially helpful for handling grammar and RTL language requirements without splitting translation strings.
Example:
Translation file:
{
+ "example": "Share your {link} with friends",
+ "link_text": "translation link"
+}
Vue template:
<template>
+ <i18n-t keypath="example">
+ <template #link>
+ <nuxt-link :to="{ name: 'referral' }">
+ <i18n-t keypath="link_text" />
+ </nuxt-link>
+ </template>
+ </i18n-t>
+</template>
This allows dynamic links within translations while preserving proper localization structure.
$fetch
limitations on SSR On serverless platforms like Vercel, $fetch
can only fetch static files from the CDN and not from the internal Nitro server. This means static translation files may not be directly accessible unless the correct base URL is set.
apiBaseUrl
If translations are hosted externally, specify the full URL (e.g., https://example.com/_locales
) for $fetch
to access the translations correctly during SSR.
Example:
{
+ // ...
+ apiBaseUrl: 'https://example.com/_locales'
+ // ...
+}
$t
or other i18n composables not work in Nuxt plugins? Nuxt I18n composables ($t
, $getLocale
, $localePath
, etc.) may not work as expected within Nuxt plugins or utility functions, resulting in runtime errors.
Cause and Solution: Nuxt composables require specific contexts (e.g., Nuxt hooks or Vue setup functions) to access the Nuxt instance. If used outside of these contexts (e.g., in utility functions or plugins), the following error might appear in the console:
[nuxt] A composable that requires access to the Nuxt instance was called outside of a plugin, Nuxt hook, Nuxt middleware, or Vue setup function. This is probably not a Nuxt bug. Find out more at https://nuxt.com/docs/guide/concepts/auto-imports#vue-and-nuxt-composables
Solution 1: Use runWithContext
To call i18n composables after an asynchronous operation, use runWithContext
to preserve the necessary context.
Example:
await nuxtApp.runWithContext(() => $t('test_key'))
Solution 2: Retrieve Value First Alternatively, retrieve the translation value first, then pass it to a utility function.
Example:
const val = nuxtApp.$t('common.errors.unknown.title')
+showError({
+ title: val
+})
Solution 3: Pass Translation Keys in Services In services or utility functions, pass the translation keys instead of using $t
directly. Then, fetch the translation in the component.
Example:
showError({
+ title: 'common.errors.unknown.title',
+ message: 'common.errors.unknown.message',
+ i18n: true
+})
These solutions help maintain context and reduce errors, allowing for flexibility in handling translations across the application.
`,50)]))}const E=i(n,[["render",l]]);export{c as __pageData,E as default}; diff --git a/assets/guide_folder-structure.md.B7ryKxoT.js b/assets/guide_folder-structure.md.B7ryKxoT.js new file mode 100644 index 00000000..24fa3ccd --- /dev/null +++ b/assets/guide_folder-structure.md.B7ryKxoT.js @@ -0,0 +1,44 @@ +import{_ as s,c as e,a2 as n,o as i}from"./chunks/framework.Gfs4HC1t.js";const u=JSON.parse('{"title":"📂 Folder Structure Guide","description":"","frontmatter":{"outline":"deep"},"headers":[],"relativePath":"guide/folder-structure.md","filePath":"guide/folder-structure.md","lastUpdated":1724243643000}'),t={name:"guide/folder-structure.md"};function o(l,a,r,p,d,c){return i(),e("div",null,a[0]||(a[0]=[n(`Organizing your translation files effectively is essential for maintaining a scalable and efficient internationalization (i18n) system. Nuxt I18n Micro
simplifies this process by offering a clear approach to managing global and page-specific translations. This guide will walk you through the recommended folder structure and explain how Nuxt I18n Micro
handles these translations.
Nuxt I18n Micro
organizes translations into global files and page-specific files within the pages
directory. This ensures that only the necessary translation data is loaded when required, optimizing both performance and organization.
Here’s a basic example of the folder structure you should follow:
/locales
+ ├── /pages
+ │ ├── /index
+ │ │ ├── en.json
+ │ │ ├── fr.json
+ │ │ └── ar.json
+ │ ├── /about
+ │ │ ├── en.json
+ │ │ ├── fr.json
+ │ │ └── ar.json
+ ├── en.json
+ ├── fr.json
+ └── ar.json
Path: /locales/{locale}.json
(e.g., /locales/en.json
)
Purpose: These files contain translations that are shared across the entire application. This is useful for common elements like navigation menus, headers, footers, or any text that appears on multiple pages.
Example Content (/locales/en.json
):
{
+ "menu": {
+ "home": "Home",
+ "about": "About Us",
+ "contact": "Contact"
+ },
+ "footer": {
+ "copyright": "© 2024 Your Company"
+ }
+}
Path: /locales/pages/{routeName}/{locale}.json
(e.g., /locales/pages/index/en.json
)
Purpose: These files are used for translations that are specific to individual pages. This allows you to load only the necessary translations when a user visits a particular page, which enhances performance by reducing the amount of data that needs to be loaded.
Example Content (/locales/pages/index/en.json
):
{
+ "title": "Welcome to Our Website",
+ "description": "We offer a wide range of products and services to meet your needs."
+}
Example Content (/locales/pages/about/en.json
):
{
+ "title": "About Us",
+ "description": "Learn more about our mission, vision, and values."
+}
Nuxt I18n Micro
automatically transforms dynamic segments and nested paths in routes into a flat folder structure using a specific renaming convention. This ensures that all translations are stored in a consistent and easily accessible manner.
When dealing with dynamic routes, such as /products/[id]
, the module converts the dynamic segment [id]
into a static format within the file structure.
Example Folder Structure for Dynamic Routes:
For a route like /products/[id]
, the translation files would be stored in a folder named products-id
:
/locales/pages
+ ├── /products-id
+ │ ├── en.json
+ │ ├── fr.json
+ │ └── ar.json
Example Folder Structure for Nested Dynamic Routes:
For a nested route like /products/key/[id]
, the translation files would be stored in a folder named products-key-id
:
/locales/pages
+ ├── /products-key-id
+ │ ├── en.json
+ │ ├── fr.json
+ │ └── ar.json
Example Folder Structure for Multi-Level Nested Routes:
For a more complex nested route like /products/category/[id]/details
, the translation files would be stored in a folder named products-category-id-details
:
/locales/pages
+ ├── /products-category-id-details
+ │ ├── en.json
+ │ ├── fr.json
+ │ └── ar.json
If you prefer to store translations in a different directory, Nuxt I18n Micro
allows you to customize the directory where translation files are stored. You can configure this in your nuxt.config.ts
file.
Example: Customizing the Translation Directory
export default defineNuxtConfig({
+ i18n: {
+ translationDir: 'i18n' // Custom directory path
+ }
+})
This will instruct Nuxt I18n Micro
to look for translation files in the /i18n
directory instead of the default /locales
directory.
Nuxt I18n Micro
uses dynamic locale routes to load translations efficiently. When a user visits a page, the module determines the appropriate locale and loads the corresponding translation files based on the current route and locale.
For example:
/en/index
will load translations from /locales/pages/index/en.json
./fr/about
will load translations from /locales/pages/about/fr.json
.This method ensures that only the necessary translations are loaded, optimizing both server load and client-side performance.
To further enhance performance, Nuxt I18n Micro
supports caching and pre-rendering of translation files:
Leverage page-specific files to avoid bloating global translation files. This keeps each page’s translations lean and fast to load, which is especially important for pages with complex or large content.
Use consistent naming conventions for your translation keys across files. This helps maintain clarity and prevents issues when managing translations, especially as your application grows.
Group related translations together within your files. For example, group all button labels under a buttons
key and all form-related texts under a forms
key. This not only improves readability but also makes it easier to manage translations across different locales.
Over time, your application might accumulate unused translation keys, especially if features are removed or restructured. Periodically review and clean up your translation files to keep them lean and maintainable.
`,49)]))}const g=s(t,[["render",o]]);export{u as __pageData,g as default}; diff --git a/assets/guide_folder-structure.md.B7ryKxoT.lean.js b/assets/guide_folder-structure.md.B7ryKxoT.lean.js new file mode 100644 index 00000000..24fa3ccd --- /dev/null +++ b/assets/guide_folder-structure.md.B7ryKxoT.lean.js @@ -0,0 +1,44 @@ +import{_ as s,c as e,a2 as n,o as i}from"./chunks/framework.Gfs4HC1t.js";const u=JSON.parse('{"title":"📂 Folder Structure Guide","description":"","frontmatter":{"outline":"deep"},"headers":[],"relativePath":"guide/folder-structure.md","filePath":"guide/folder-structure.md","lastUpdated":1724243643000}'),t={name:"guide/folder-structure.md"};function o(l,a,r,p,d,c){return i(),e("div",null,a[0]||(a[0]=[n(`Organizing your translation files effectively is essential for maintaining a scalable and efficient internationalization (i18n) system. Nuxt I18n Micro
simplifies this process by offering a clear approach to managing global and page-specific translations. This guide will walk you through the recommended folder structure and explain how Nuxt I18n Micro
handles these translations.
Nuxt I18n Micro
organizes translations into global files and page-specific files within the pages
directory. This ensures that only the necessary translation data is loaded when required, optimizing both performance and organization.
Here’s a basic example of the folder structure you should follow:
/locales
+ ├── /pages
+ │ ├── /index
+ │ │ ├── en.json
+ │ │ ├── fr.json
+ │ │ └── ar.json
+ │ ├── /about
+ │ │ ├── en.json
+ │ │ ├── fr.json
+ │ │ └── ar.json
+ ├── en.json
+ ├── fr.json
+ └── ar.json
Path: /locales/{locale}.json
(e.g., /locales/en.json
)
Purpose: These files contain translations that are shared across the entire application. This is useful for common elements like navigation menus, headers, footers, or any text that appears on multiple pages.
Example Content (/locales/en.json
):
{
+ "menu": {
+ "home": "Home",
+ "about": "About Us",
+ "contact": "Contact"
+ },
+ "footer": {
+ "copyright": "© 2024 Your Company"
+ }
+}
Path: /locales/pages/{routeName}/{locale}.json
(e.g., /locales/pages/index/en.json
)
Purpose: These files are used for translations that are specific to individual pages. This allows you to load only the necessary translations when a user visits a particular page, which enhances performance by reducing the amount of data that needs to be loaded.
Example Content (/locales/pages/index/en.json
):
{
+ "title": "Welcome to Our Website",
+ "description": "We offer a wide range of products and services to meet your needs."
+}
Example Content (/locales/pages/about/en.json
):
{
+ "title": "About Us",
+ "description": "Learn more about our mission, vision, and values."
+}
Nuxt I18n Micro
automatically transforms dynamic segments and nested paths in routes into a flat folder structure using a specific renaming convention. This ensures that all translations are stored in a consistent and easily accessible manner.
When dealing with dynamic routes, such as /products/[id]
, the module converts the dynamic segment [id]
into a static format within the file structure.
Example Folder Structure for Dynamic Routes:
For a route like /products/[id]
, the translation files would be stored in a folder named products-id
:
/locales/pages
+ ├── /products-id
+ │ ├── en.json
+ │ ├── fr.json
+ │ └── ar.json
Example Folder Structure for Nested Dynamic Routes:
For a nested route like /products/key/[id]
, the translation files would be stored in a folder named products-key-id
:
/locales/pages
+ ├── /products-key-id
+ │ ├── en.json
+ │ ├── fr.json
+ │ └── ar.json
Example Folder Structure for Multi-Level Nested Routes:
For a more complex nested route like /products/category/[id]/details
, the translation files would be stored in a folder named products-category-id-details
:
/locales/pages
+ ├── /products-category-id-details
+ │ ├── en.json
+ │ ├── fr.json
+ │ └── ar.json
If you prefer to store translations in a different directory, Nuxt I18n Micro
allows you to customize the directory where translation files are stored. You can configure this in your nuxt.config.ts
file.
Example: Customizing the Translation Directory
export default defineNuxtConfig({
+ i18n: {
+ translationDir: 'i18n' // Custom directory path
+ }
+})
This will instruct Nuxt I18n Micro
to look for translation files in the /i18n
directory instead of the default /locales
directory.
Nuxt I18n Micro
uses dynamic locale routes to load translations efficiently. When a user visits a page, the module determines the appropriate locale and loads the corresponding translation files based on the current route and locale.
For example:
/en/index
will load translations from /locales/pages/index/en.json
./fr/about
will load translations from /locales/pages/about/fr.json
.This method ensures that only the necessary translations are loaded, optimizing both server load and client-side performance.
To further enhance performance, Nuxt I18n Micro
supports caching and pre-rendering of translation files:
Leverage page-specific files to avoid bloating global translation files. This keeps each page’s translations lean and fast to load, which is especially important for pages with complex or large content.
Use consistent naming conventions for your translation keys across files. This helps maintain clarity and prevents issues when managing translations, especially as your application grows.
Group related translations together within your files. For example, group all button labels under a buttons
key and all form-related texts under a forms
key. This not only improves readability but also makes it easier to manage translations across different locales.
Over time, your application might accumulate unused translation keys, especially if features are removed or restructured. Periodically review and clean up your translation files to keep them lean and maintainable.
`,49)]))}const g=s(t,[["render",o]]);export{u as __pageData,g as default}; diff --git a/assets/guide_getting-started.md.DMTe_ufE.js b/assets/guide_getting-started.md.DMTe_ufE.js new file mode 100644 index 00000000..58004bbb --- /dev/null +++ b/assets/guide_getting-started.md.DMTe_ufE.js @@ -0,0 +1,74 @@ +import{_ as i,c as a,a2 as e,o as t}from"./chunks/framework.Gfs4HC1t.js";const c=JSON.parse('{"title":"🌐 Getting Started with Nuxt I18n Micro","description":"","frontmatter":{"outline":"deep"},"headers":[],"relativePath":"guide/getting-started.md","filePath":"guide/getting-started.md","lastUpdated":1736853461000}'),n={name:"guide/getting-started.md"};function l(p,s,h,o,r,d){return t(),a("div",null,s[0]||(s[0]=[e(`Nuxt I18n Micro
is a lightweight internationalization module for Nuxt that delivers superior performance compared to traditional solutions. It's designed to reduce build times, memory usage, and server load, making it ideal for high-traffic and large projects.
Here are some key benefits of using Nuxt I18n Micro
:
To install the module in your Nuxt application, run the following command:
npm install nuxt-i18n-micro
After installation, add the module to your nuxt.config.ts
file:
export default defineNuxtConfig({
+ modules: [
+ 'nuxt-i18n-micro',
+ ],
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-US', dir: 'ltr' },
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr' },
+ { code: 'ar', iso: 'ar-SA', dir: 'rtl' },
+ ],
+ defaultLocale: 'en',
+ translationDir: 'locales',
+ meta: true,
+ },
+})
Translation files are organized into global and page-specific directories:
/locales
+ ├── /pages
+ │ ├── /index
+ │ │ ├── en.json
+ │ │ ├── fr.json
+ │ │ └── ar.json
+ │ ├── /about
+ │ │ ├── en.json
+ │ │ ├── fr.json
+ │ │ └── ar.json
+ ├── en.json
+ ├── fr.json
+ └── ar.json
The Nuxt I18n Micro
module provides a range of customizable options to fine-tune your internationalization setup:
Here’s the updated documentation for locales
, including the new baseUrl
and baseDefault
properties:
locales
Defines the locales available in your application.
Type: Locale[]
Each locale object can include the following properties:
code
(string, required): A unique identifier for the locale, e.g., 'en'
for English.iso
(string, optional): The ISO code for the locale, such as 'en-US'
. This can be used for the lang
attribute in HTML to help with accessibility and SEO.dir
(string, optional): Specifies the text direction for the locale, either 'ltr'
(left-to-right) or 'rtl'
(right-to-left).disabled
(boolean, optional): Disables the locale in the dropdown if set to true
, preventing users from selecting it.baseUrl
(string, optional): Sets a base URL for the locale, which should be used to configure redirection for locale-specific domains or subdomains. The actual redirection implementation should be handled in layers outside of this configuration, as setting baseUrl
alone means all links within the project will direct to the specified domain. Additionally, this parameter requires an explicit protocol, either http
or https
.baseDefault
(boolean, optional): If set to true
, the locale's routes do not include the locale code in the URL path, making it the default locale.Example:
locales: [
+ { code: 'en', iso: 'en-US', dir: 'ltr' },
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr' },
+ { code: 'ar', iso: 'ar-SA', dir: 'rtl', disabled: true },
+ { code: 'de', iso: 'de-DE', dir: 'ltr', baseUrl: 'https://de.example.com', baseDefault: true },
+ { code: 'es', iso: 'es-ES', dir: 'ltr', baseUrl: 'https://es.example.com', baseDefault: true },
+ { code: 'ja', iso: 'ja-JP', dir: 'ltr', baseUrl: 'https://new.example.com' }
+]
In this example:
ar
locale is disabled.de
and es
each have their own baseUrl
and baseDefault
, meaning routes for these locales will start with their respective URLs (https://de.example.com
, https://es.example.com
).ja
each have their own baseUrl
, meaning routes for these locales will start with their respective URLs (https://new.example.com/ja
).Additional Notes:
baseUrl
is provided, it will override the default routing structure, adding the baseUrl
prefix to all routes for that locale. However, using baseUrl
is generally not recommended, as it can lead to duplication of all internal routes as external links, complicating routing and maintenance. Instead, it is often simpler and more manageable to create external links directly for specific locales.baseDefault
is set to true
, the specified locale's URLs will not include the locale code prefix, making it appear as the primary or default language. Note that baseDefault
works only in combination with baseUrl
.defaultLocale
Sets the default locale if no specific locale is selected by the user.
Type: string
Example:
defaultLocale: 'en'
translationDir
Specifies the directory where translation files are stored.
Type: string
Default: 'locales'
Example:
translationDir: 'i18n' // Custom directory for translation files
meta
Automatically generates SEO-related meta tags, such as alternate
links for different locales.
Type: boolean
Default: true
Example:
meta: true // Enable automatic SEO meta tags generation
debug
Enables logging and debugging information during the generation process to help with troubleshooting.
Type: boolean
Default: false
Example:
debug: true // Enable logging and debugging information
types
Adds types to the project during the postinstall process. If you encounter issues with types, you can disable this option.
Type: boolean
Default: true
Example:
types: true
metaBaseUrl
Sets the base URL for generating SEO-related meta tags like canonical and alternate URLs.
Type: string
Default: '/'
Example:
metaBaseUrl: 'https://example.com' // Custom base URL for meta tags
autoDetectLanguage
Automatically detects the user's preferred language based on browser settings and redirects to the appropriate locale.
Type: boolean
Default: false
Example:
autoDetectLanguage: true // Enable automatic language detection and redirection
autoDetectPath
Specifies the route path(s) on which locale auto-detection and switching should occur.
Type: string
Default: "/"
Description:
Defines the route(s) where locale detection is active. By default, locale detection happens only on the home route ("/"
).
Setting this to "*"
enables locale detection on all routes. However, using "*"
may cause unexpected issues, especially if cookies are disabled, as this can interfere with tracking the user's locale preference.
plural
Custom function for handling pluralization in translations based on count and locale.
Type: (key: string, count: number, params: Record<string, string | number | boolean>, locale: string, t: Getter) => string
Example:
export type Getter = (key: string, params?: Record<string, string | number | boolean>, defaultValue?: string) => unknown
+
+{
+ plural: (key: string, count: number, _params: Record<string, string | number | boolean>, _locale: string, t: Getter) => {
+ const translation = t(key)
+ if (!translation) {
+ return key
+ }
+ const forms = translation.toString().split('|')
+ return (count < forms.length ? forms[count].trim() : forms[forms.length - 1].trim()).replace('{count}', count.toString())
+ }
+}
includeDefaultLocaleRoute
(Deprecated)
Automatically redirects routes without a locale prefix to the default locale.
Type: boolean
Default: false
Deprecated: As of version 1.50.0, includeDefaultLocaleRoute
is deprecated. Use the strategy
option instead for more flexible route handling.
strategy
Version introduced: v1.50.0
Defines how locale prefixes should be handled in routes. Choose the strategy that best fits your use case.
Type: string
Default: prefix_and_default
Available Strategies:
no_prefix
Routes will not have a locale prefix. The locale will be detected and changed without modifying the URL. Locale detection relies on the browser and cookies, and you need to manage locale switching through the i18n API.
Note: This strategy does not support features like Custom paths or Ignore routes.
prefix_except_default
A locale prefix will be added to all routes, except for the default language. URLs for the default language will not include a prefix.
prefix
All routes will include a locale prefix, regardless of the language.
prefix_and_default
Combines both previous behaviors. URLs for every language will have a locale prefix, while URLs for the default language will have a non-prefixed version. However, if detectBrowserLanguage
is enabled, the prefixed version will be preferred for the default language.
customRegexMatcher
I18n-micro meticulously checks each locale via vue-router route regex. If you have a lot of locales, you can improve pattern matching performances via a custom regex matcher.
Type: string | RegExp
Default: false
Example:
customRegexMatcher: '[a-z]-[A-Z]'// This matches locales in isoCode (e.g: '/en-US', 'de-DE' etc)
routesLocaleLinks
Creates links between different pages' locale files to share translations, reducing duplication.
Type: Record<string, string>
Example:
{
+ routesLocaleLinks: {
+ 'products-id': 'products',
+ 'about-us': 'about'
+ }
+}
define
Enables or disables the addition of a special define
plugin that allows you to use Nuxt's runtime configuration for overriding settings in your translation files.
Type: boolean
Default: true
Example:
define: false // Disable the define plugin
plugin
Enables or disables a special plugin
that integrates additional features or functionality into your Nuxt application.
Type: boolean
Default: true
Example:
plugin: false // Disable the plugin
disablePageLocales
Allows you to disable page-specific translations, limiting the module to only use global translation files.
Type: boolean
Default: false
Example:
disablePageLocales: true // Disable page-specific translations, using only global translations
disablePageLocales: true
When disablePageLocales
is enabled, the module will only use the translations defined in the global files located directly under the locales
directory. Page-specific translation files (located in /locales/pages
) will be ignored.
/locales
+ ├── en.json
+ ├── fr.json
+ └── ar.json
disableWatcher
Disables the automatic creation of locale files during development.
Type: boolean
Default: false
Example:
disableWatcher: true // Disables the automatic creation of locale files
disableUpdater
Version introduced: v1.60.0
Disables the file watcher for updating store items during development.
Type: boolean
Default: false
Example:
disableUpdater: true // Disables the file watcher for updating store items
apiBaseUrl
env: NUXT_I18N_APP_BASE_URL
Defines the base URL that the server will use to fetch cached translations. By default, this is set to _locales
, but you can change it to any custom path, such as api/_locales
, if you want to load translations from a different endpoint.
Type: string
Default: '_locales'
Example:
apiBaseUrl: 'api/_locales' // Custom URL for fetching cached translations
When set, the module will use the specified URL to request cached translations instead of using the default _locales
.
localeCookie
Specifies the name of the cookie used to store the user's selected locale.
Type: string
Default: 'user-locale'
fallbackLocale
Specifies a fallback locale to be used when the current locale does not have a specific translation available.
Type: string | undefined
Default: undefined
Example:
{
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-US', dir: 'ltr' },
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr' },
+ { code: 'es', iso: 'es-ES', dir: 'ltr' }
+ ],
+ defaultLocale: 'en',
+ // Use English as a fallback locale
+ fallbackLocale: 'en'
+ }
+}
globalLocaleRoutes
Allows you to define custom localized routes for specific pages. You can specify a custom path for each locale for a given page, or disable localization for certain pages entirely.
Type: Record<string, Record<string, string> | false>
string
): The name of the page you want to customize or disable localization for.Record<string, string>
: A set of locale codes with corresponding custom paths for the page.false
: Disable localization for this page entirely. The page will not be localized, and it will remain accessible only through its default path.This option gives you the flexibility to localize certain pages differently while leaving others unaffected by localization.
Example:
{
+ globalLocaleRoutes: {
+ page2: {
+ en: '/custom-page2-en',
+ de: '/custom-page2-de',
+ ru: '/custom-page2-ru'
+ },
+ // Unlocalized page should not be localized
+ unlocalized: false
+ }
+}
In the example above:
page2
: Custom localized paths are defined for the page page2
in English (en
), German (de
), and Russian (ru
). Instead of following the standard localization pattern (like /en/page2
), each locale will have a completely custom URL, such as /en/custom-page2-en
for English, /de/custom-page2-de
for German, and /ru/custom-page2-ru
for Russian.unlocalized
: This page will not be localized, so it remains accessible only at /unlocalized
, without any locale prefixes or custom paths.One of the standout features of Nuxt I18n Micro
is its intelligent caching system. When a translation is requested during server-side rendering (SSR), the result is stored in a cache. This means that subsequent requests for the same translation can
retrieve the data from the cache rather than searching through the translation files again. This caching mechanism drastically reduces the time needed to fetch translations and significantly lowers the server's resource consumption.
`,154)]))}const g=i(n,[["render",l]]);export{c as __pageData,g as default}; diff --git a/assets/guide_getting-started.md.DMTe_ufE.lean.js b/assets/guide_getting-started.md.DMTe_ufE.lean.js new file mode 100644 index 00000000..58004bbb --- /dev/null +++ b/assets/guide_getting-started.md.DMTe_ufE.lean.js @@ -0,0 +1,74 @@ +import{_ as i,c as a,a2 as e,o as t}from"./chunks/framework.Gfs4HC1t.js";const c=JSON.parse('{"title":"🌐 Getting Started with Nuxt I18n Micro","description":"","frontmatter":{"outline":"deep"},"headers":[],"relativePath":"guide/getting-started.md","filePath":"guide/getting-started.md","lastUpdated":1736853461000}'),n={name:"guide/getting-started.md"};function l(p,s,h,o,r,d){return t(),a("div",null,s[0]||(s[0]=[e(`Nuxt I18n Micro
is a lightweight internationalization module for Nuxt that delivers superior performance compared to traditional solutions. It's designed to reduce build times, memory usage, and server load, making it ideal for high-traffic and large projects.
Here are some key benefits of using Nuxt I18n Micro
:
To install the module in your Nuxt application, run the following command:
npm install nuxt-i18n-micro
After installation, add the module to your nuxt.config.ts
file:
export default defineNuxtConfig({
+ modules: [
+ 'nuxt-i18n-micro',
+ ],
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-US', dir: 'ltr' },
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr' },
+ { code: 'ar', iso: 'ar-SA', dir: 'rtl' },
+ ],
+ defaultLocale: 'en',
+ translationDir: 'locales',
+ meta: true,
+ },
+})
Translation files are organized into global and page-specific directories:
/locales
+ ├── /pages
+ │ ├── /index
+ │ │ ├── en.json
+ │ │ ├── fr.json
+ │ │ └── ar.json
+ │ ├── /about
+ │ │ ├── en.json
+ │ │ ├── fr.json
+ │ │ └── ar.json
+ ├── en.json
+ ├── fr.json
+ └── ar.json
The Nuxt I18n Micro
module provides a range of customizable options to fine-tune your internationalization setup:
Here’s the updated documentation for locales
, including the new baseUrl
and baseDefault
properties:
locales
Defines the locales available in your application.
Type: Locale[]
Each locale object can include the following properties:
code
(string, required): A unique identifier for the locale, e.g., 'en'
for English.iso
(string, optional): The ISO code for the locale, such as 'en-US'
. This can be used for the lang
attribute in HTML to help with accessibility and SEO.dir
(string, optional): Specifies the text direction for the locale, either 'ltr'
(left-to-right) or 'rtl'
(right-to-left).disabled
(boolean, optional): Disables the locale in the dropdown if set to true
, preventing users from selecting it.baseUrl
(string, optional): Sets a base URL for the locale, which should be used to configure redirection for locale-specific domains or subdomains. The actual redirection implementation should be handled in layers outside of this configuration, as setting baseUrl
alone means all links within the project will direct to the specified domain. Additionally, this parameter requires an explicit protocol, either http
or https
.baseDefault
(boolean, optional): If set to true
, the locale's routes do not include the locale code in the URL path, making it the default locale.Example:
locales: [
+ { code: 'en', iso: 'en-US', dir: 'ltr' },
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr' },
+ { code: 'ar', iso: 'ar-SA', dir: 'rtl', disabled: true },
+ { code: 'de', iso: 'de-DE', dir: 'ltr', baseUrl: 'https://de.example.com', baseDefault: true },
+ { code: 'es', iso: 'es-ES', dir: 'ltr', baseUrl: 'https://es.example.com', baseDefault: true },
+ { code: 'ja', iso: 'ja-JP', dir: 'ltr', baseUrl: 'https://new.example.com' }
+]
In this example:
ar
locale is disabled.de
and es
each have their own baseUrl
and baseDefault
, meaning routes for these locales will start with their respective URLs (https://de.example.com
, https://es.example.com
).ja
each have their own baseUrl
, meaning routes for these locales will start with their respective URLs (https://new.example.com/ja
).Additional Notes:
baseUrl
is provided, it will override the default routing structure, adding the baseUrl
prefix to all routes for that locale. However, using baseUrl
is generally not recommended, as it can lead to duplication of all internal routes as external links, complicating routing and maintenance. Instead, it is often simpler and more manageable to create external links directly for specific locales.baseDefault
is set to true
, the specified locale's URLs will not include the locale code prefix, making it appear as the primary or default language. Note that baseDefault
works only in combination with baseUrl
.defaultLocale
Sets the default locale if no specific locale is selected by the user.
Type: string
Example:
defaultLocale: 'en'
translationDir
Specifies the directory where translation files are stored.
Type: string
Default: 'locales'
Example:
translationDir: 'i18n' // Custom directory for translation files
meta
Automatically generates SEO-related meta tags, such as alternate
links for different locales.
Type: boolean
Default: true
Example:
meta: true // Enable automatic SEO meta tags generation
debug
Enables logging and debugging information during the generation process to help with troubleshooting.
Type: boolean
Default: false
Example:
debug: true // Enable logging and debugging information
types
Adds types to the project during the postinstall process. If you encounter issues with types, you can disable this option.
Type: boolean
Default: true
Example:
types: true
metaBaseUrl
Sets the base URL for generating SEO-related meta tags like canonical and alternate URLs.
Type: string
Default: '/'
Example:
metaBaseUrl: 'https://example.com' // Custom base URL for meta tags
autoDetectLanguage
Automatically detects the user's preferred language based on browser settings and redirects to the appropriate locale.
Type: boolean
Default: false
Example:
autoDetectLanguage: true // Enable automatic language detection and redirection
autoDetectPath
Specifies the route path(s) on which locale auto-detection and switching should occur.
Type: string
Default: "/"
Description:
Defines the route(s) where locale detection is active. By default, locale detection happens only on the home route ("/"
).
Setting this to "*"
enables locale detection on all routes. However, using "*"
may cause unexpected issues, especially if cookies are disabled, as this can interfere with tracking the user's locale preference.
plural
Custom function for handling pluralization in translations based on count and locale.
Type: (key: string, count: number, params: Record<string, string | number | boolean>, locale: string, t: Getter) => string
Example:
export type Getter = (key: string, params?: Record<string, string | number | boolean>, defaultValue?: string) => unknown
+
+{
+ plural: (key: string, count: number, _params: Record<string, string | number | boolean>, _locale: string, t: Getter) => {
+ const translation = t(key)
+ if (!translation) {
+ return key
+ }
+ const forms = translation.toString().split('|')
+ return (count < forms.length ? forms[count].trim() : forms[forms.length - 1].trim()).replace('{count}', count.toString())
+ }
+}
includeDefaultLocaleRoute
(Deprecated)
Automatically redirects routes without a locale prefix to the default locale.
Type: boolean
Default: false
Deprecated: As of version 1.50.0, includeDefaultLocaleRoute
is deprecated. Use the strategy
option instead for more flexible route handling.
strategy
Version introduced: v1.50.0
Defines how locale prefixes should be handled in routes. Choose the strategy that best fits your use case.
Type: string
Default: prefix_and_default
Available Strategies:
no_prefix
Routes will not have a locale prefix. The locale will be detected and changed without modifying the URL. Locale detection relies on the browser and cookies, and you need to manage locale switching through the i18n API.
Note: This strategy does not support features like Custom paths or Ignore routes.
prefix_except_default
A locale prefix will be added to all routes, except for the default language. URLs for the default language will not include a prefix.
prefix
All routes will include a locale prefix, regardless of the language.
prefix_and_default
Combines both previous behaviors. URLs for every language will have a locale prefix, while URLs for the default language will have a non-prefixed version. However, if detectBrowserLanguage
is enabled, the prefixed version will be preferred for the default language.
customRegexMatcher
I18n-micro meticulously checks each locale via vue-router route regex. If you have a lot of locales, you can improve pattern matching performances via a custom regex matcher.
Type: string | RegExp
Default: false
Example:
customRegexMatcher: '[a-z]-[A-Z]'// This matches locales in isoCode (e.g: '/en-US', 'de-DE' etc)
routesLocaleLinks
Creates links between different pages' locale files to share translations, reducing duplication.
Type: Record<string, string>
Example:
{
+ routesLocaleLinks: {
+ 'products-id': 'products',
+ 'about-us': 'about'
+ }
+}
define
Enables or disables the addition of a special define
plugin that allows you to use Nuxt's runtime configuration for overriding settings in your translation files.
Type: boolean
Default: true
Example:
define: false // Disable the define plugin
plugin
Enables or disables a special plugin
that integrates additional features or functionality into your Nuxt application.
Type: boolean
Default: true
Example:
plugin: false // Disable the plugin
disablePageLocales
Allows you to disable page-specific translations, limiting the module to only use global translation files.
Type: boolean
Default: false
Example:
disablePageLocales: true // Disable page-specific translations, using only global translations
disablePageLocales: true
When disablePageLocales
is enabled, the module will only use the translations defined in the global files located directly under the locales
directory. Page-specific translation files (located in /locales/pages
) will be ignored.
/locales
+ ├── en.json
+ ├── fr.json
+ └── ar.json
disableWatcher
Disables the automatic creation of locale files during development.
Type: boolean
Default: false
Example:
disableWatcher: true // Disables the automatic creation of locale files
disableUpdater
Version introduced: v1.60.0
Disables the file watcher for updating store items during development.
Type: boolean
Default: false
Example:
disableUpdater: true // Disables the file watcher for updating store items
apiBaseUrl
env: NUXT_I18N_APP_BASE_URL
Defines the base URL that the server will use to fetch cached translations. By default, this is set to _locales
, but you can change it to any custom path, such as api/_locales
, if you want to load translations from a different endpoint.
Type: string
Default: '_locales'
Example:
apiBaseUrl: 'api/_locales' // Custom URL for fetching cached translations
When set, the module will use the specified URL to request cached translations instead of using the default _locales
.
localeCookie
Specifies the name of the cookie used to store the user's selected locale.
Type: string
Default: 'user-locale'
fallbackLocale
Specifies a fallback locale to be used when the current locale does not have a specific translation available.
Type: string | undefined
Default: undefined
Example:
{
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-US', dir: 'ltr' },
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr' },
+ { code: 'es', iso: 'es-ES', dir: 'ltr' }
+ ],
+ defaultLocale: 'en',
+ // Use English as a fallback locale
+ fallbackLocale: 'en'
+ }
+}
globalLocaleRoutes
Allows you to define custom localized routes for specific pages. You can specify a custom path for each locale for a given page, or disable localization for certain pages entirely.
Type: Record<string, Record<string, string> | false>
string
): The name of the page you want to customize or disable localization for.Record<string, string>
: A set of locale codes with corresponding custom paths for the page.false
: Disable localization for this page entirely. The page will not be localized, and it will remain accessible only through its default path.This option gives you the flexibility to localize certain pages differently while leaving others unaffected by localization.
Example:
{
+ globalLocaleRoutes: {
+ page2: {
+ en: '/custom-page2-en',
+ de: '/custom-page2-de',
+ ru: '/custom-page2-ru'
+ },
+ // Unlocalized page should not be localized
+ unlocalized: false
+ }
+}
In the example above:
page2
: Custom localized paths are defined for the page page2
in English (en
), German (de
), and Russian (ru
). Instead of following the standard localization pattern (like /en/page2
), each locale will have a completely custom URL, such as /en/custom-page2-en
for English, /de/custom-page2-de
for German, and /ru/custom-page2-ru
for Russian.unlocalized
: This page will not be localized, so it remains accessible only at /unlocalized
, without any locale prefixes or custom paths.One of the standout features of Nuxt I18n Micro
is its intelligent caching system. When a translation is requested during server-side rendering (SSR), the result is stored in a cache. This means that subsequent requests for the same translation can
retrieve the data from the cache rather than searching through the translation files again. This caching mechanism drastically reduces the time needed to fetch translations and significantly lowers the server's resource consumption.
`,154)]))}const g=i(n,[["render",l]]);export{c as __pageData,g as default}; diff --git a/assets/guide_layers.md.Bs1rVVV1.js b/assets/guide_layers.md.Bs1rVVV1.js new file mode 100644 index 00000000..b2c8f6de --- /dev/null +++ b/assets/guide_layers.md.Bs1rVVV1.js @@ -0,0 +1,72 @@ +import{_ as i,c as a,a2 as n,o as t}from"./chunks/framework.Gfs4HC1t.js";const o=JSON.parse('{"title":"🗂️ Layers in Nuxt I18n Micro","description":"","frontmatter":{"outline":"deep"},"headers":[],"relativePath":"guide/layers.md","filePath":"guide/layers.md","lastUpdated":1724243643000}'),e={name:"guide/layers.md"};function l(h,s,p,k,r,E){return t(),a("div",null,s[0]||(s[0]=[n(`Nuxt I18n Micro
Layers in Nuxt I18n Micro
allow you to manage and customize localization settings flexibly across different parts of your application. By defining different layers, you can adjust the configuration for various contexts, such as overriding settings for specific sections of your site or creating reusable base configurations that can be extended by other parts of your application.
The Primary Configuration Layer is where you set up the default localization settings for your entire application. This layer is essential as it defines the global configuration, including the supported locales, default language, and other critical i18n settings.
Here’s an example of how you might define the primary configuration layer in your nuxt.config.ts
file:
export default defineNuxtConfig({
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-EN', dir: 'ltr' },
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr' },
+ { code: 'ar', iso: 'ar-SA', dir: 'rtl' },
+ ],
+ defaultLocale: 'en', // The default locale for the entire app
+ translationDir: 'locales', // Directory where translations are stored
+ meta: true, // Automatically generate SEO-related meta tags like \`alternate\`
+ autoDetectLanguage: true, // Automatically detect and use the user's preferred language
+ },
+})
Child layers are used to extend or override the primary configuration for specific parts of your application. For instance, you might want to add additional locales or modify the default locale for a particular section of your site. Child layers are especially useful in modular applications where different parts of the application might have different localization requirements.
Suppose you have a section of your site that needs to support additional locales, or you want to disable a particular locale in a certain context. Here’s how you can achieve that by extending the primary configuration layer:
// basic/nuxt.config.ts (Primary Layer)
+export default defineNuxtConfig({
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-EN', dir: 'ltr' },
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr' },
+ ],
+ defaultLocale: 'en',
+ meta: true,
+ translationDir: 'locales',
+ },
+})
// extended/nuxt.config.ts (Child Layer)
+export default defineNuxtConfig({
+ extends: '../basic', // Inherit the base configuration from the 'basic' layer
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-EN', dir: 'ltr' }, // Inherited from the base layer
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr' }, // Inherited from the base layer
+ { code: 'de', iso: 'de-DE', dir: 'ltr' }, // Added in the child layer
+ ],
+ defaultLocale: 'fr', // Override the default locale to French for this section
+ autoDetectLanguage: false, // Disable automatic language detection in this section
+ },
+})
In a larger, modular Nuxt application, you might have multiple sections, each requiring its own i18n settings. By leveraging layers, you can maintain a clean and scalable configuration structure.
Imagine you have an e-commerce site with distinct sections like the main website, admin panel, and customer support portal. Each section might need a different set of locales or other i18n settings.
// nuxt.config.ts
+export default defineNuxtConfig({
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-EN', dir: 'ltr' },
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr' },
+ ],
+ defaultLocale: 'en',
+ meta: true,
+ translationDir: 'locales',
+ autoDetectLanguage: true,
+ },
+})
// admin/nuxt.config.ts
+export default defineNuxtConfig({
+ extends: '../nuxt.config', // Inherit the global settings
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-EN', dir: 'ltr' }, // Inherited
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr' }, // Inherited
+ { code: 'es', iso: 'es-ES', dir: 'ltr' }, // Specific to the admin panel
+ ],
+ defaultLocale: 'en',
+ meta: false, // Disable automatic meta generation in the admin panel
+ },
+})
// support/nuxt.config.ts
+export default defineNuxtConfig({
+ extends: '../nuxt.config', // Inherit the global settings
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-EN', dir: 'ltr' }, // Inherited
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr' }, // Inherited
+ { code: 'de', iso: 'de-DE', dir: 'ltr' }, // Specific to the support portal
+ ],
+ defaultLocale: 'de', // Default to German in the support portal
+ autoDetectLanguage: false, // Disable automatic language detection
+ },
+})
In this modular example:
es
) as a locale and disables meta tag generation.de
) as a locale and defaults to German for the user interface.Nuxt I18n Micro
Layers in Nuxt I18n Micro
allow you to manage and customize localization settings flexibly across different parts of your application. By defining different layers, you can adjust the configuration for various contexts, such as overriding settings for specific sections of your site or creating reusable base configurations that can be extended by other parts of your application.
The Primary Configuration Layer is where you set up the default localization settings for your entire application. This layer is essential as it defines the global configuration, including the supported locales, default language, and other critical i18n settings.
Here’s an example of how you might define the primary configuration layer in your nuxt.config.ts
file:
export default defineNuxtConfig({
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-EN', dir: 'ltr' },
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr' },
+ { code: 'ar', iso: 'ar-SA', dir: 'rtl' },
+ ],
+ defaultLocale: 'en', // The default locale for the entire app
+ translationDir: 'locales', // Directory where translations are stored
+ meta: true, // Automatically generate SEO-related meta tags like \`alternate\`
+ autoDetectLanguage: true, // Automatically detect and use the user's preferred language
+ },
+})
Child layers are used to extend or override the primary configuration for specific parts of your application. For instance, you might want to add additional locales or modify the default locale for a particular section of your site. Child layers are especially useful in modular applications where different parts of the application might have different localization requirements.
Suppose you have a section of your site that needs to support additional locales, or you want to disable a particular locale in a certain context. Here’s how you can achieve that by extending the primary configuration layer:
// basic/nuxt.config.ts (Primary Layer)
+export default defineNuxtConfig({
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-EN', dir: 'ltr' },
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr' },
+ ],
+ defaultLocale: 'en',
+ meta: true,
+ translationDir: 'locales',
+ },
+})
// extended/nuxt.config.ts (Child Layer)
+export default defineNuxtConfig({
+ extends: '../basic', // Inherit the base configuration from the 'basic' layer
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-EN', dir: 'ltr' }, // Inherited from the base layer
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr' }, // Inherited from the base layer
+ { code: 'de', iso: 'de-DE', dir: 'ltr' }, // Added in the child layer
+ ],
+ defaultLocale: 'fr', // Override the default locale to French for this section
+ autoDetectLanguage: false, // Disable automatic language detection in this section
+ },
+})
In a larger, modular Nuxt application, you might have multiple sections, each requiring its own i18n settings. By leveraging layers, you can maintain a clean and scalable configuration structure.
Imagine you have an e-commerce site with distinct sections like the main website, admin panel, and customer support portal. Each section might need a different set of locales or other i18n settings.
// nuxt.config.ts
+export default defineNuxtConfig({
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-EN', dir: 'ltr' },
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr' },
+ ],
+ defaultLocale: 'en',
+ meta: true,
+ translationDir: 'locales',
+ autoDetectLanguage: true,
+ },
+})
// admin/nuxt.config.ts
+export default defineNuxtConfig({
+ extends: '../nuxt.config', // Inherit the global settings
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-EN', dir: 'ltr' }, // Inherited
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr' }, // Inherited
+ { code: 'es', iso: 'es-ES', dir: 'ltr' }, // Specific to the admin panel
+ ],
+ defaultLocale: 'en',
+ meta: false, // Disable automatic meta generation in the admin panel
+ },
+})
// support/nuxt.config.ts
+export default defineNuxtConfig({
+ extends: '../nuxt.config', // Inherit the global settings
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-EN', dir: 'ltr' }, // Inherited
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr' }, // Inherited
+ { code: 'de', iso: 'de-DE', dir: 'ltr' }, // Specific to the support portal
+ ],
+ defaultLocale: 'de', // Default to German in the support portal
+ autoDetectLanguage: false, // Disable automatic language detection
+ },
+})
In this modular example:
es
) as a locale and disables meta tag generation.de
) as a locale and defaults to German for the user interface.nuxt-i18n
to Nuxt I18n Micro
Migrating from nuxt-i18n
to Nuxt I18n Micro
can significantly improve the performance of your Nuxt application, especially in high-traffic environments or projects with large translation files. This guide provides a step-by-step approach to help you smoothly transition from nuxt-i18n
to Nuxt I18n Micro
.
The Nuxt I18n Micro
module offers several advantages over the traditional nuxt-i18n
:
Before you begin the migration process, it’s essential to understand the key differences between nuxt-i18n
and Nuxt I18n Micro
:
Nuxt I18n Micro
uses dynamic regex-based routing, generating only two routes regardless of the number of locales, unlike nuxt-i18n
which creates a separate route for each locale.Nuxt I18n Micro
. The translations are split into global and page-specific files, which are auto-generated in development mode if not present.Nuxt I18n Micro
offers built-in SEO optimization with automatic meta tag generation and support for hreflang
tags.Nuxt I18n Micro
First, add Nuxt I18n Micro
to your Nuxt project:
npm install nuxt-i18n-micro
Replace your existing nuxt-i18n
configuration in nuxt.config.ts
with the Nuxt I18n Micro
configuration. Here’s an example:
Before (nuxt-i18n):
export default defineNuxtConfig({
+ modules: ['nuxt-i18n'],
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-US' },
+ { code: 'fr', iso: 'fr-FR' },
+ ],
+ defaultLocale: 'en',
+ vueI18n: './i18n.config.js',
+ },
+})
After (Nuxt I18n Micro):
export default defineNuxtConfig({
+ modules: ['nuxt-i18n-micro'],
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-US', dir: 'ltr' },
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr' },
+ ],
+ defaultLocale: 'en',
+ translationDir: 'locales',
+ meta: true,
+ },
+})
Move your translation files to the locales
directory. Ensure they are in JSON format and organized by locale. For example:
/locales
+ ├── /pages
+ │ ├── /index
+ │ │ ├── en.json
+ │ │ ├── fr.json
+ │ │ └── ar.json
+ │ ├── /about
+ │ │ ├── en.json
+ │ │ ├── fr.json
+ │ │ └── ar.json
+ ├── en.json
+ ├── fr.json
+ └── ar.json
<nuxt-link>
with <NuxtLink>
If you are using <nuxt-link>
for navigation, replace it with <NuxtLink>
to ensure compatibility with the new module.
Before:
<nuxt-link :to="{ name: 'index' }">Home</nuxt-link>
After:
<NuxtLink :to="$localeRoute({ name: 'index' })">Home</NuxtLink>
+<!-- or -->
+<i18n-link :to="{ name: 'index' }">Home</i18n-link>
Ensure that your SEO configurations are updated to take advantage of Nuxt I18n Micro
’s automatic meta tag generation. Remove any redundant SEO configurations that were specific to nuxt-i18n
.
After completing the migration steps, thoroughly test your application to ensure that all translations are loading correctly and that navigation between locales works as expected. Pay special attention to SEO-related tags and ensure that they are generated as intended.
Ensure that your translation files are in the correct directory and follow the JSON format. Also, confirm that the translationDir
option in your configuration matches the location of your translation files.
Check that the routes are correctly set up in your application and that the locales
array in the configuration includes all necessary locale codes.
If SEO tags are not being generated, verify that the meta
option is enabled in your configuration and that each locale has a valid iso
code.
nuxt-i18n
to Nuxt I18n Micro
Migrating from nuxt-i18n
to Nuxt I18n Micro
can significantly improve the performance of your Nuxt application, especially in high-traffic environments or projects with large translation files. This guide provides a step-by-step approach to help you smoothly transition from nuxt-i18n
to Nuxt I18n Micro
.
The Nuxt I18n Micro
module offers several advantages over the traditional nuxt-i18n
:
Before you begin the migration process, it’s essential to understand the key differences between nuxt-i18n
and Nuxt I18n Micro
:
Nuxt I18n Micro
uses dynamic regex-based routing, generating only two routes regardless of the number of locales, unlike nuxt-i18n
which creates a separate route for each locale.Nuxt I18n Micro
. The translations are split into global and page-specific files, which are auto-generated in development mode if not present.Nuxt I18n Micro
offers built-in SEO optimization with automatic meta tag generation and support for hreflang
tags.Nuxt I18n Micro
First, add Nuxt I18n Micro
to your Nuxt project:
npm install nuxt-i18n-micro
Replace your existing nuxt-i18n
configuration in nuxt.config.ts
with the Nuxt I18n Micro
configuration. Here’s an example:
Before (nuxt-i18n):
export default defineNuxtConfig({
+ modules: ['nuxt-i18n'],
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-US' },
+ { code: 'fr', iso: 'fr-FR' },
+ ],
+ defaultLocale: 'en',
+ vueI18n: './i18n.config.js',
+ },
+})
After (Nuxt I18n Micro):
export default defineNuxtConfig({
+ modules: ['nuxt-i18n-micro'],
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-US', dir: 'ltr' },
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr' },
+ ],
+ defaultLocale: 'en',
+ translationDir: 'locales',
+ meta: true,
+ },
+})
Move your translation files to the locales
directory. Ensure they are in JSON format and organized by locale. For example:
/locales
+ ├── /pages
+ │ ├── /index
+ │ │ ├── en.json
+ │ │ ├── fr.json
+ │ │ └── ar.json
+ │ ├── /about
+ │ │ ├── en.json
+ │ │ ├── fr.json
+ │ │ └── ar.json
+ ├── en.json
+ ├── fr.json
+ └── ar.json
<nuxt-link>
with <NuxtLink>
If you are using <nuxt-link>
for navigation, replace it with <NuxtLink>
to ensure compatibility with the new module.
Before:
<nuxt-link :to="{ name: 'index' }">Home</nuxt-link>
After:
<NuxtLink :to="$localeRoute({ name: 'index' })">Home</NuxtLink>
+<!-- or -->
+<i18n-link :to="{ name: 'index' }">Home</i18n-link>
Ensure that your SEO configurations are updated to take advantage of Nuxt I18n Micro
’s automatic meta tag generation. Remove any redundant SEO configurations that were specific to nuxt-i18n
.
After completing the migration steps, thoroughly test your application to ensure that all translations are loading correctly and that navigation between locales works as expected. Pay special attention to SEO-related tags and ensure that they are generated as intended.
Ensure that your translation files are in the correct directory and follow the JSON format. Also, confirm that the translationDir
option in your configuration matches the location of your translation files.
Check that the routes are correctly set up in your application and that the locales
array in the configuration includes all necessary locale codes.
If SEO tags are not being generated, verify that the meta
option is enabled in your configuration and that each locale has a valid iso
code.
Nuxt I18n Micro
Using Layers By leveraging layers in Nuxt I18n Micro
, you can create a flexible and maintainable multi-domain localization setup. This approach not only simplifies domain management by eliminating the need for complex functionalities but also allows for efficient load distribution and reduced project complexity. By running separate projects for different locales, your application can easily scale and adapt to varying locale requirements across multiple domains, offering a robust and scalable solution for global applications.
To create a setup where different domains serve specific locales by customizing configurations in child layers. This method leverages Nuxt's layering system, allowing you to maintain a base configuration while extending or modifying it for each domain.
Start by creating a base configuration layer that includes all the common locale settings for your application. This configuration will serve as the foundation for other domain-specific configurations.
Create the base configuration file base/nuxt.config.ts
:
// base/nuxt.config.ts
+
+export default defineNuxtConfig({
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-US', dir: 'ltr' },
+ { code: 'de', iso: 'de-DE', dir: 'ltr' },
+ { code: 'es', iso: 'es-ES', dir: 'ltr' },
+ ],
+ defaultLocale: 'en',
+ translationDir: 'locales',
+ meta: true,
+ autoDetectLanguage: true,
+ },
+})
For each domain, create a child layer that modifies the base configuration to meet the specific requirements of that domain. You can disable locales that are not needed for a specific domain.
Create a child layer configuration for the French domain in fr/nuxt.config.ts
:
// fr/nuxt.config.ts
+
+export default defineNuxtConfig({
+ extends: '../base', // Inherit from the base configuration
+
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-US', dir: 'ltr', disabled: true }, // Disable English
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr' }, // Add and enable the French locale
+ { code: 'de', iso: 'de-DE', dir: 'ltr', disabled: true }, // Disable German
+ { code: 'es', iso: 'es-ES', dir: 'ltr', disabled: true }, // Disable Spanish
+ ],
+ defaultLocale: 'fr', // Set French as the default locale
+ autoDetectLanguage: false, // Disable automatic language detection
+ },
+})
Similarly, create a child layer configuration for the German domain in de/nuxt.config.ts
:
// de/nuxt.config.ts
+
+export default defineNuxtConfig({
+ extends: '../base', // Inherit from the base configuration
+
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-US', dir: 'ltr', disabled: true }, // Disable English
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr', disabled: true }, // Disable French
+ { code: 'de', iso: 'de-DE', dir: 'ltr' }, // Use the German locale
+ { code: 'es', iso: 'es-ES', dir: 'ltr', disabled: true }, // Disable Spanish
+ ],
+ defaultLocale: 'de', // Set German as the default locale
+ autoDetectLanguage: false, // Disable automatic language detection
+ },
+})
Deploy the application with the appropriate configuration for each domain. For example:
fr
layer configuration to fr.example.com
.de
layer configuration to de.example.com
.For each locale and domain, you'll need to run a separate instance of the application. This ensures that each domain serves the correct locale configuration, optimizing the load distribution and simplifying the project's structure. By running multiple projects tailored to each locale, you can maintain a clean separation between configurations and reduce the complexity of the overall setup.
Ensure that your routing is configured to direct users to the correct project based on the domain they are accessing. This will ensure that each domain serves the appropriate locale, enhancing user experience and maintaining consistency across different regions.
After configuring the layers and deploying them to their respective domains, ensure each domain is serving the correct locale. Test the application thoroughly to confirm that the correct locale is loaded depending on the domain.
By leveraging layers in Nuxt I18n Micro
, you can create a flexible and maintainable multi-domain localization setup. This approach not only eliminates the need for complex domain management functionalities but also allows you to distribute the load efficiently and reduce project complexity. Running separate projects for different locales ensures that your application can scale easily and adapt to different locale requirements across various domains, providing a robust and scalable solution for global applications.
Nuxt I18n Micro
Using Layers By leveraging layers in Nuxt I18n Micro
, you can create a flexible and maintainable multi-domain localization setup. This approach not only simplifies domain management by eliminating the need for complex functionalities but also allows for efficient load distribution and reduced project complexity. By running separate projects for different locales, your application can easily scale and adapt to varying locale requirements across multiple domains, offering a robust and scalable solution for global applications.
To create a setup where different domains serve specific locales by customizing configurations in child layers. This method leverages Nuxt's layering system, allowing you to maintain a base configuration while extending or modifying it for each domain.
Start by creating a base configuration layer that includes all the common locale settings for your application. This configuration will serve as the foundation for other domain-specific configurations.
Create the base configuration file base/nuxt.config.ts
:
// base/nuxt.config.ts
+
+export default defineNuxtConfig({
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-US', dir: 'ltr' },
+ { code: 'de', iso: 'de-DE', dir: 'ltr' },
+ { code: 'es', iso: 'es-ES', dir: 'ltr' },
+ ],
+ defaultLocale: 'en',
+ translationDir: 'locales',
+ meta: true,
+ autoDetectLanguage: true,
+ },
+})
For each domain, create a child layer that modifies the base configuration to meet the specific requirements of that domain. You can disable locales that are not needed for a specific domain.
Create a child layer configuration for the French domain in fr/nuxt.config.ts
:
// fr/nuxt.config.ts
+
+export default defineNuxtConfig({
+ extends: '../base', // Inherit from the base configuration
+
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-US', dir: 'ltr', disabled: true }, // Disable English
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr' }, // Add and enable the French locale
+ { code: 'de', iso: 'de-DE', dir: 'ltr', disabled: true }, // Disable German
+ { code: 'es', iso: 'es-ES', dir: 'ltr', disabled: true }, // Disable Spanish
+ ],
+ defaultLocale: 'fr', // Set French as the default locale
+ autoDetectLanguage: false, // Disable automatic language detection
+ },
+})
Similarly, create a child layer configuration for the German domain in de/nuxt.config.ts
:
// de/nuxt.config.ts
+
+export default defineNuxtConfig({
+ extends: '../base', // Inherit from the base configuration
+
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-US', dir: 'ltr', disabled: true }, // Disable English
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr', disabled: true }, // Disable French
+ { code: 'de', iso: 'de-DE', dir: 'ltr' }, // Use the German locale
+ { code: 'es', iso: 'es-ES', dir: 'ltr', disabled: true }, // Disable Spanish
+ ],
+ defaultLocale: 'de', // Set German as the default locale
+ autoDetectLanguage: false, // Disable automatic language detection
+ },
+})
Deploy the application with the appropriate configuration for each domain. For example:
fr
layer configuration to fr.example.com
.de
layer configuration to de.example.com
.For each locale and domain, you'll need to run a separate instance of the application. This ensures that each domain serves the correct locale configuration, optimizing the load distribution and simplifying the project's structure. By running multiple projects tailored to each locale, you can maintain a clean separation between configurations and reduce the complexity of the overall setup.
Ensure that your routing is configured to direct users to the correct project based on the domain they are accessing. This will ensure that each domain serves the appropriate locale, enhancing user experience and maintaining consistency across different regions.
After configuring the layers and deploying them to their respective domains, ensure each domain is serving the correct locale. Test the application thoroughly to confirm that the correct locale is loaded depending on the domain.
By leveraging layers in Nuxt I18n Micro
, you can create a flexible and maintainable multi-domain localization setup. This approach not only eliminates the need for complex domain management functionalities but also allows you to distribute the load efficiently and reduce project complexity. Running separate projects for different locales ensures that your application can scale easily and adapt to different locale requirements across various domains, providing a robust and scalable solution for global applications.
Nuxt I18n Micro
Per-Component Translations
in Nuxt I18n Micro
allows developers to define translations directly within specific components or pages of a Nuxt application using the $defineI18nRoute
function. This approach is ideal for managing localized content that is unique to individual components, providing a more modular and maintainable method for handling translations.
$defineI18nRoute
Function The $defineI18nRoute
function configures route behavior based on the current locale, offering a versatile solution to:
$defineI18nRoute(routeDefinition: {
+ locales?: string[] | Record<string, Record<string, TranslationObject>>,
+ localeRoutes?: Record<string, string>
+})
locales: Defines which locales are available for the route. This can be:
['en', 'fr', 'de']
).localeRoutes: Allows custom routes for specific locales. Each key represents a locale code, and the value is the custom route path for that locale. This is useful for scenarios where different locales require unique routing.
$defineI18nRoute({
+ locales: {
+ en: { greeting: 'Hello', farewell: 'Goodbye' },
+ ru: { greeting: 'Привет', farewell: 'До свидания' },
+ de: { greeting: 'Hallo', farewell: 'Auf Wiedersehen' },
+ },
+ localeRoutes: {
+ ru: '/localesubpage', // Custom route path for the Russian locale
+ },
+})
Controlling Access Based on Locales: Define which locales are allowed for specific routes to ensure users only see content relevant to their language.
import { useNuxtApp } from '#imports'
+
+const { $defineI18nRoute } = useNuxtApp()
+
+$defineI18nRoute({
+ locales: ['en', 'fr', 'de'] // Only these locales are allowed for this route
+})
Providing Translations for Locales: Use the locales
object to provide specific translations for each route, enhancing the user experience by delivering content in the user's preferred language.
import { useNuxtApp } from '#imports'
+
+const { $defineI18nRoute } = useNuxtApp()
+
+$defineI18nRoute({
+ locales: {
+ en: { greeting: 'Hello', farewell: 'Goodbye' },
+ fr: { greeting: 'Bonjour', farewell: 'Au revoir' },
+ de: { greeting: 'Hallo', farewell: { aaa: { bbb: "Auf Wiedersehen" } } },
+ ru: {} // Russian locale is allowed but no translations are provided
+ }
+})
Custom Routing for Locales: Define custom paths for specific locales using the localeRoutes
property. This allows you to create unique navigational flows or URL structures for different languages or regions.
locales
property when specific translations or access control based on locales are required.Here's an example of a Vue page using defineI18nRoute
for per-component translations:
Below is an example of how to use $defineI18nRoute
within a Vue component to handle translations and custom routing based on locale.
<template>
+ <div>
+ <h1>{{ t('greeting') }}</h1>
+ <p>{{ t('farewell') }}</p>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { useNuxtApp } from '#imports'
+
+// Access the $defineI18nRoute function from Nuxt's context
+const { $defineI18nRoute, $t: t } = useNuxtApp()
+
+// Define i18n route with translations for specific locales
+$defineI18nRoute({
+ locales: {
+ en: { greeting: 'Hello', farewell: 'Goodbye' },
+ fr: { greeting: 'Bonjour', farewell: 'Au revoir' },
+ de: { greeting: 'Hallo', farewell: 'Auf Wiedersehen' },
+ ru: { greeting: 'Привет', farewell: 'До свидания' },
+ },
+ localeRoutes: {
+ ru: '/ru-specific-path', // Custom route path for the Russian locale
+ fr: '/fr-specific-path' // Custom route path for the French locale
+ }
+})
+</script>
locales
property of $defineI18nRoute
. This keeps translations closely tied to the component, making them easy to manage and update.localeRoutes
property is used to set specific paths for different locales. This allows for unique navigational flows based on the user's language preference.This setup enables the component to display localized greetings and farewells based on the current locale, and it also allows for custom routes tailored to specific locales, enhancing the user experience by delivering content in the preferred language and structure.
The Per-Component Translations
feature, powered by the $defineI18nRoute
function, offers a powerful and flexible way to manage localization within your Nuxt application. By allowing localized content and routing to be defined at the component level, it helps create a highly customized and user-friendly experience tailored to the language and regional preferences of your audience.
Nuxt I18n Micro
Per-Component Translations
in Nuxt I18n Micro
allows developers to define translations directly within specific components or pages of a Nuxt application using the $defineI18nRoute
function. This approach is ideal for managing localized content that is unique to individual components, providing a more modular and maintainable method for handling translations.
$defineI18nRoute
Function The $defineI18nRoute
function configures route behavior based on the current locale, offering a versatile solution to:
$defineI18nRoute(routeDefinition: {
+ locales?: string[] | Record<string, Record<string, TranslationObject>>,
+ localeRoutes?: Record<string, string>
+})
locales: Defines which locales are available for the route. This can be:
['en', 'fr', 'de']
).localeRoutes: Allows custom routes for specific locales. Each key represents a locale code, and the value is the custom route path for that locale. This is useful for scenarios where different locales require unique routing.
$defineI18nRoute({
+ locales: {
+ en: { greeting: 'Hello', farewell: 'Goodbye' },
+ ru: { greeting: 'Привет', farewell: 'До свидания' },
+ de: { greeting: 'Hallo', farewell: 'Auf Wiedersehen' },
+ },
+ localeRoutes: {
+ ru: '/localesubpage', // Custom route path for the Russian locale
+ },
+})
Controlling Access Based on Locales: Define which locales are allowed for specific routes to ensure users only see content relevant to their language.
import { useNuxtApp } from '#imports'
+
+const { $defineI18nRoute } = useNuxtApp()
+
+$defineI18nRoute({
+ locales: ['en', 'fr', 'de'] // Only these locales are allowed for this route
+})
Providing Translations for Locales: Use the locales
object to provide specific translations for each route, enhancing the user experience by delivering content in the user's preferred language.
import { useNuxtApp } from '#imports'
+
+const { $defineI18nRoute } = useNuxtApp()
+
+$defineI18nRoute({
+ locales: {
+ en: { greeting: 'Hello', farewell: 'Goodbye' },
+ fr: { greeting: 'Bonjour', farewell: 'Au revoir' },
+ de: { greeting: 'Hallo', farewell: { aaa: { bbb: "Auf Wiedersehen" } } },
+ ru: {} // Russian locale is allowed but no translations are provided
+ }
+})
Custom Routing for Locales: Define custom paths for specific locales using the localeRoutes
property. This allows you to create unique navigational flows or URL structures for different languages or regions.
locales
property when specific translations or access control based on locales are required.Here's an example of a Vue page using defineI18nRoute
for per-component translations:
Below is an example of how to use $defineI18nRoute
within a Vue component to handle translations and custom routing based on locale.
<template>
+ <div>
+ <h1>{{ t('greeting') }}</h1>
+ <p>{{ t('farewell') }}</p>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { useNuxtApp } from '#imports'
+
+// Access the $defineI18nRoute function from Nuxt's context
+const { $defineI18nRoute, $t: t } = useNuxtApp()
+
+// Define i18n route with translations for specific locales
+$defineI18nRoute({
+ locales: {
+ en: { greeting: 'Hello', farewell: 'Goodbye' },
+ fr: { greeting: 'Bonjour', farewell: 'Au revoir' },
+ de: { greeting: 'Hallo', farewell: 'Auf Wiedersehen' },
+ ru: { greeting: 'Привет', farewell: 'До свидания' },
+ },
+ localeRoutes: {
+ ru: '/ru-specific-path', // Custom route path for the Russian locale
+ fr: '/fr-specific-path' // Custom route path for the French locale
+ }
+})
+</script>
locales
property of $defineI18nRoute
. This keeps translations closely tied to the component, making them easy to manage and update.localeRoutes
property is used to set specific paths for different locales. This allows for unique navigational flows based on the user's language preference.This setup enables the component to display localized greetings and farewells based on the current locale, and it also allows for custom routes tailored to specific locales, enhancing the user experience by delivering content in the preferred language and structure.
The Per-Component Translations
feature, powered by the $defineI18nRoute
function, offers a powerful and flexible way to manage localization within your Nuxt application. By allowing localized content and routing to be defined at the component level, it helps create a highly customized and user-friendly experience tailored to the language and regional preferences of your audience.
This performance test compares two implementations of internationalization: i18n-micro and i18n. The main focus of the test is to evaluate build times, memory usage, CPU usage, and the performance of the server under stress (e.g., how many requests can be handled and how efficiently). The i18n-micro implementation shows slightly lower overall script execution times. This difference is attributed to its ability to handle more requests, which requires additional time for processing.
It is essential to recognize that the example used in this test is not entirely representative of the intended usage pattern for i18n-micro. The example simplifies the translation structure by consolidating all translations into a single file. However, i18n-micro is optimized for scenarios where translations are organized on a per-page basis. This approach allows for more granular control and efficiency, particularly in large-scale applications. The current setup is used merely for demonstration purposes and may not fully showcase the potential performance benefits of i18n-micro in real-world applications.
Dependency | Version |
---|---|
node | v20.18.0 |
nuxt | ^3.15.2 |
nuxt-i18n-micro | 1.64.0 |
@nuxtjs/i18n | ^9.1.1 |
The performance tests conducted for Nuxt I18n Micro
and nuxt-i18n
v9 are designed to simulate real-world usage scenarios. Below is an overview of the key aspects of the test methodology:
The chosen testing methodology is designed to reflect the scenarios that developers are likely to encounter in production environments. By focusing on build time, CPU and memory usage, and server performance under load, the tests provide a comprehensive view of how each module will perform in a large-scale, high-traffic application.
Nuxt I18n Micro is optimized for:
This performance test compares two implementations of internationalization: i18n-micro and i18n. The main focus of the test is to evaluate build times, memory usage, CPU usage, and the performance of the server under stress (e.g., how many requests can be handled and how efficiently). The i18n-micro implementation shows slightly lower overall script execution times. This difference is attributed to its ability to handle more requests, which requires additional time for processing.
It is essential to recognize that the example used in this test is not entirely representative of the intended usage pattern for i18n-micro. The example simplifies the translation structure by consolidating all translations into a single file. However, i18n-micro is optimized for scenarios where translations are organized on a per-page basis. This approach allows for more granular control and efficiency, particularly in large-scale applications. The current setup is used merely for demonstration purposes and may not fully showcase the potential performance benefits of i18n-micro in real-world applications.
Dependency | Version |
---|---|
node | v20.18.0 |
nuxt | ^3.15.2 |
nuxt-i18n-micro | 1.64.0 |
@nuxtjs/i18n | ^9.1.1 |
The performance tests conducted for Nuxt I18n Micro
and nuxt-i18n
v9 are designed to simulate real-world usage scenarios. Below is an overview of the key aspects of the test methodology:
The chosen testing methodology is designed to reflect the scenarios that developers are likely to encounter in production environments. By focusing on build time, CPU and memory usage, and server performance under load, the tests provide a comprehensive view of how each module will perform in a large-scale, high-traffic application.
Nuxt I18n Micro is optimized for:
Nuxt I18n Micro
is designed with performance in mind, offering a significant improvement over traditional internationalization (i18n) modules like nuxt-i18n
. This guide provides an in-depth look at the performance benefits of using Nuxt I18n Micro
, and how it compares to other solutions.
In large-scale projects and high-traffic environments, performance bottlenecks can lead to slow build times, increased memory usage, and poor server response times. These issues become more pronounced with complex i18n setups involving large translation files. Nuxt I18n Micro
was built to address these challenges head-on by optimizing for speed, memory efficiency, and minimal impact on your application’s bundle size.
We conducted a series of tests to demonstrate the performance improvements that Nuxt I18n Micro
brings to the table. Below is a detailed comparison between Nuxt I18n Micro
and the traditional nuxt-i18n
module, based on identical conditions with a 10MB translation file on the same hardware.
Nuxt I18n Micro
We also tested server performance by simulating 10,000 requests to each module.
Nuxt I18n Micro
These tests clearly indicate that Nuxt I18n Micro
offers superior performance across multiple metrics:
Nuxt I18n Micro
is built around a minimalist architecture, using only 5 components (1 module and 4 plugins). This reduces overhead and simplifies the internal logic, leading to improved performance.
Unlike other i18n modules that generate a separate route for each locale, Nuxt I18n Micro
uses dynamic regex-based routing. This approach generates only two routes regardless of the number of locales, significantly reducing the complexity of your routing configuration and speeding up route resolution.
The module supports only JSON files for translations, with a clear separation between global and page-specific files. This ensures that only the necessary translation data is loaded at any given time, further enhancing performance.
To optimize performance, Nuxt I18n Micro
implements caching and supports pre-rendering of translation files:
Here are a few tips to ensure you get the best performance out of Nuxt I18n Micro
:
For detailed results of the performance tests, please refer to the Performance Test Results.
',31)]))}const p=r(i,[["render",t]]);export{g as __pageData,p as default}; diff --git a/assets/guide_performance.md.CbRsZzqQ.lean.js b/assets/guide_performance.md.CbRsZzqQ.lean.js new file mode 100644 index 00000000..79d37e81 --- /dev/null +++ b/assets/guide_performance.md.CbRsZzqQ.lean.js @@ -0,0 +1 @@ +import{_ as r,c as o,a2 as n,o as a}from"./chunks/framework.Gfs4HC1t.js";const g=JSON.parse('{"title":"🚀 Performance Guide","description":"","frontmatter":{"outline":"deep"},"headers":[],"relativePath":"guide/performance.md","filePath":"guide/performance.md","lastUpdated":1724679268000}'),i={name:"guide/performance.md"};function t(s,e,l,c,d,u){return a(),o("div",null,e[0]||(e[0]=[n('Nuxt I18n Micro
is designed with performance in mind, offering a significant improvement over traditional internationalization (i18n) modules like nuxt-i18n
. This guide provides an in-depth look at the performance benefits of using Nuxt I18n Micro
, and how it compares to other solutions.
In large-scale projects and high-traffic environments, performance bottlenecks can lead to slow build times, increased memory usage, and poor server response times. These issues become more pronounced with complex i18n setups involving large translation files. Nuxt I18n Micro
was built to address these challenges head-on by optimizing for speed, memory efficiency, and minimal impact on your application’s bundle size.
We conducted a series of tests to demonstrate the performance improvements that Nuxt I18n Micro
brings to the table. Below is a detailed comparison between Nuxt I18n Micro
and the traditional nuxt-i18n
module, based on identical conditions with a 10MB translation file on the same hardware.
Nuxt I18n Micro
We also tested server performance by simulating 10,000 requests to each module.
Nuxt I18n Micro
These tests clearly indicate that Nuxt I18n Micro
offers superior performance across multiple metrics:
Nuxt I18n Micro
is built around a minimalist architecture, using only 5 components (1 module and 4 plugins). This reduces overhead and simplifies the internal logic, leading to improved performance.
Unlike other i18n modules that generate a separate route for each locale, Nuxt I18n Micro
uses dynamic regex-based routing. This approach generates only two routes regardless of the number of locales, significantly reducing the complexity of your routing configuration and speeding up route resolution.
The module supports only JSON files for translations, with a clear separation between global and page-specific files. This ensures that only the necessary translation data is loaded at any given time, further enhancing performance.
To optimize performance, Nuxt I18n Micro
implements caching and supports pre-rendering of translation files:
Here are a few tips to ensure you get the best performance out of Nuxt I18n Micro
:
For detailed results of the performance tests, please refer to the Performance Test Results.
',31)]))}const p=r(i,[["render",t]]);export{g as __pageData,p as default}; diff --git a/assets/guide_seo.md.CjeG8qHD.js b/assets/guide_seo.md.CjeG8qHD.js new file mode 100644 index 00000000..f1d1c66e --- /dev/null +++ b/assets/guide_seo.md.CjeG8qHD.js @@ -0,0 +1,13 @@ +import{_ as e,c as s,a2 as a,o as n}from"./chunks/framework.Gfs4HC1t.js";const k=JSON.parse('{"title":"🌐 SEO Guide for Nuxt I18n Micro","description":"","frontmatter":{"outline":"deep"},"headers":[],"relativePath":"guide/seo.md","filePath":"guide/seo.md","lastUpdated":1724243643000}'),t={name:"guide/seo.md"};function l(o,i,r,h,d,p){return n(),s("div",null,i[0]||(i[0]=[a(`Effective SEO (Search Engine Optimization) is essential for ensuring that your multilingual site is accessible and visible to users worldwide through search engines. Nuxt I18n Micro
simplifies the process of managing SEO for multilingual sites by automatically generating essential meta tags and attributes that inform search engines about the structure and content of your site.
This guide explains how Nuxt I18n Micro
handles SEO to enhance your site's visibility and user experience without requiring additional configuration.
When the meta
option is enabled in Nuxt I18n Micro
, the module automatically manages the following SEO aspects:
🌍 Language and Direction Attributes:
lang
and dir
attributes on the <html>
tag according to the current locale and text direction (e.g., ltr
for English or rtl
for Arabic).🔗 Canonical URLs:
<link rel="canonical">
) for each page, ensuring that search engines recognize the primary version of the content.🌐 Alternate Language Links (hreflang
):
<link rel="alternate" hreflang="">
tags for all available locales. This helps search engines understand which language versions of your content are available, improving the user experience for global audiences.🔖 Open Graph Metadata:
og:locale
, og:url
, etc.) for each locale, which is particularly useful for social media sharing and search engine indexing.To enable these SEO features, ensure the meta
option is set to true
in your nuxt.config.ts
file:
export default defineNuxtConfig({
+ modules: ['nuxt-i18n-micro'],
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-US', dir: 'ltr' },
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr' },
+ { code: 'ar', iso: 'ar-SA', dir: 'rtl' },
+ ],
+ defaultLocale: 'en',
+ translationDir: 'locales',
+ meta: true, // Enables automatic SEO management
+ },
+})
By enabling the meta
option, you benefit from:
Effective SEO (Search Engine Optimization) is essential for ensuring that your multilingual site is accessible and visible to users worldwide through search engines. Nuxt I18n Micro
simplifies the process of managing SEO for multilingual sites by automatically generating essential meta tags and attributes that inform search engines about the structure and content of your site.
This guide explains how Nuxt I18n Micro
handles SEO to enhance your site's visibility and user experience without requiring additional configuration.
When the meta
option is enabled in Nuxt I18n Micro
, the module automatically manages the following SEO aspects:
🌍 Language and Direction Attributes:
lang
and dir
attributes on the <html>
tag according to the current locale and text direction (e.g., ltr
for English or rtl
for Arabic).🔗 Canonical URLs:
<link rel="canonical">
) for each page, ensuring that search engines recognize the primary version of the content.🌐 Alternate Language Links (hreflang
):
<link rel="alternate" hreflang="">
tags for all available locales. This helps search engines understand which language versions of your content are available, improving the user experience for global audiences.🔖 Open Graph Metadata:
og:locale
, og:url
, etc.) for each locale, which is particularly useful for social media sharing and search engine indexing.To enable these SEO features, ensure the meta
option is set to true
in your nuxt.config.ts
file:
export default defineNuxtConfig({
+ modules: ['nuxt-i18n-micro'],
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-US', dir: 'ltr' },
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr' },
+ { code: 'ar', iso: 'ar-SA', dir: 'rtl' },
+ ],
+ defaultLocale: 'en',
+ translationDir: 'locales',
+ meta: true, // Enables automatic SEO management
+ },
+})
By enabling the meta
option, you benefit from:
Nuxt I18n Micro supports server-side translations, allowing you to translate content on the server and return it as part of the response. This is particularly useful for APIs or server-rendered applications where localization is needed before reaching the client.
The translations use locale messages defined in the Nuxt I18n configuration and are dynamically resolved based on the detected locale.
To clarify, the translations used by Nuxt I18n Micro in server-side handling are only sourced from the root-level translation files. Any nested translation files or subdirectories are not utilized in this context. The system will only retrieve translations from the root folder, ensuring a consistent and manageable approach to server-side translation retrieval.
To enable server-side translations, use the provided middleware to handle locale detection and return translations dynamically. The useTranslationServerMiddleware
function is designed for this purpose.
You can seamlessly translate content in any eventHandler
by using the middleware.
import { defineEventHandler } from 'h3'
+
+export default defineEventHandler(async (event) => {
+ const t = await useTranslationServerMiddleware(event)
+ return {
+ message: t('greeting'), // Returns the translated value for the key "greeting"
+ }
+})
In this example:
t
function retrieves the appropriate translation for the detected locale.If you need to specify a locale manually (e.g., for testing or certain requests), you can pass it to the middleware:
import { defineEventHandler } from 'h3'
+
+function detectLocale(event): string | null {
+ const urlSearchParams = new URLSearchParams(event.node.req.url?.split('?')[1]);
+ const localeFromQuery = urlSearchParams.get('locale');
+ if (localeFromQuery) return localeFromQuery;
+
+ return 'en';
+}
+
+export default defineEventHandler(async (event) => {
+ const t = await useTranslationServerMiddleware(event, 'en', detectLocale(event)) // Force French local, en - default locale
+ return {
+ message: t('welcome'), // Returns the French translation for "welcome"
+ }
+})
The middleware automatically determines the user's locale using a fallback chain:
?locale=fr
user-locale
Accept-Language
Nuxt I18n Micro supports server-side translations, allowing you to translate content on the server and return it as part of the response. This is particularly useful for APIs or server-rendered applications where localization is needed before reaching the client.
The translations use locale messages defined in the Nuxt I18n configuration and are dynamically resolved based on the detected locale.
To clarify, the translations used by Nuxt I18n Micro in server-side handling are only sourced from the root-level translation files. Any nested translation files or subdirectories are not utilized in this context. The system will only retrieve translations from the root folder, ensuring a consistent and manageable approach to server-side translation retrieval.
To enable server-side translations, use the provided middleware to handle locale detection and return translations dynamically. The useTranslationServerMiddleware
function is designed for this purpose.
You can seamlessly translate content in any eventHandler
by using the middleware.
import { defineEventHandler } from 'h3'
+
+export default defineEventHandler(async (event) => {
+ const t = await useTranslationServerMiddleware(event)
+ return {
+ message: t('greeting'), // Returns the translated value for the key "greeting"
+ }
+})
In this example:
t
function retrieves the appropriate translation for the detected locale.If you need to specify a locale manually (e.g., for testing or certain requests), you can pass it to the middleware:
import { defineEventHandler } from 'h3'
+
+function detectLocale(event): string | null {
+ const urlSearchParams = new URLSearchParams(event.node.req.url?.split('?')[1]);
+ const localeFromQuery = urlSearchParams.get('locale');
+ if (localeFromQuery) return localeFromQuery;
+
+ return 'en';
+}
+
+export default defineEventHandler(async (event) => {
+ const t = await useTranslationServerMiddleware(event, 'en', detectLocale(event)) // Force French local, en - default locale
+ return {
+ message: t('welcome'), // Returns the French translation for "welcome"
+ }
+})
The middleware automatically determines the user's locale using a fallback chain:
?locale=fr
user-locale
Accept-Language
Nuxt I18n
(Version 1.50.0+) Starting with version 1.50.0, Nuxt I18n
introduces a more flexible way to manage how locale prefixes are handled in URLs through the strategy
option. This new approach replaces the deprecated includeDefaultLocaleRoute
and gives you better control over how localization is applied to different routes in your application.
The strategy
option allows you to choose between different behaviors regarding locale prefixes, providing more fine-grained control over the URLs of your application and how they are structured based on the user's selected language.
strategy
(New in Version 1.50.0) The strategy
option defines how locale prefixes should be managed across your routes. The available strategies give you varying levels of control over how the locale appears in the URLs.
Type: string
Default: prefix_and_default
This strategy ensures that no locale prefix is added to your routes. Instead of modifying the URL, the application will detect and change the locale based on the user's browser settings or cookies.
Default Locale: You can set the default locale using an environment variable. For example:
DEFAULT_LOCALE=de npm run dev
DEFAULT_LOCALE=de npm run build
Use Case: Ideal when you want a cleaner URL structure and are relying on automatic language detection rather than explicit locale identifiers in the URL.
i18n: {
+ strategy: 'no_prefix'
+}
Example Routes:
/about
(for any language, e.g., en
, ru
, fr
, etc.)/contact
(for any language)/other
(for any language)/other2
(for any language)With this strategy, all of your routes will include a locale prefix, except for the default language. For the default language, the route will appear without any prefix.
Use Case: Useful when you want all non-default languages to have a distinct URL structure with a locale prefix but prefer the default language to be accessible without the prefix.
i18n: {
+ strategy: 'prefix_except_default'
+}
Example Routes:
/about
(for the default language, e.g., en
)/ru/about
(for Russian)/fr/about
(for French)This strategy ensures that every route in your application will include a locale prefix, regardless of the language. It standardizes the URL structure across all languages.
Use Case: Ideal for situations where you want a consistent URL structure for all languages, ensuring every route includes the locale prefix.
i18n: {
+ strategy: 'prefix'
+}
Example Routes:
/en/about
(for English)/ru/about
(for Russian)/fr/about
(for French)This strategy combines both the prefix
and prefix_except_default
behaviors. It ensures that all languages have a locale prefix in their URLs, but the default language also has a non-prefixed URL version available. When the detectBrowserLanguage
feature is enabled, the prefixed version of the default language will be preferred.
Use Case: Best for applications that want to support both prefixed and non-prefixed URLs for the default language while maintaining a locale prefix for other languages.
i18n: {
+ strategy: 'prefix_and_default'
+}
Example Routes:
/about
(for the default language, e.g., en
)/en/about
(for English, with prefix)/ru/about
(for Russian)/fr/about
(for French)While the strategy
option provides flexibility, there are some known issues and best practices to keep in mind when using these strategies.
no_prefix
Strategy with Static Generation When using the no_prefix
strategy in combination with static site generation (generate
mode), you may encounter a hydration mismatch error. This happens because the locale is determined dynamically (e.g., via cookies or browser settings) after the static page is rendered, leading to a mismatch between the server-rendered content and the client-side hydration.
Error Example:
Hydration completed but contains mismatches.
Workaround:
prefix_except_default
or prefix
if static generation is a requirement.localeRoute
and Route Resolution When using localeRoute
to generate links, there can be issues with route resolution, especially if you rely on path-based routing. For example:
localeRoute('/page') // May cause issues with route resolution
Best Practice:
localeRoute
to avoid unnecessary redirects or route resolution problems:localeRoute({ name: 'page' }) // Preferred approach
This ensures that the correct route is resolved regardless of the locale strategy.
no_prefix
Strategy In the no_prefix
strategy, rendering content that depends on the selected locale (e.g., buttons for switching languages) can lead to issues. For example, if you use a v-for
loop to render locale buttons, Vue may incorrectly apply the disabled
attribute due to hydration mismatches.
Example Problematic Code:
<button
+ v-for="locale in availableLocales"
+ :key="locale.code"
+ :disabled="locale.isActive"
+ :class="{ disabled: locale.isActive }"
+ @click="() => $switchLocale(locale.code)"
+>
+ Switch to {{ locale.code }}
+</button>
Issue:
disabled
attribute during hydration, and it may not update correctly when the locale changes.Best Practice:
<select>
element or another approach that avoids direct DOM manipulation for locale-dependent content:<select @change="(e) => $switchLocale(e.target.value)">
+ <option
+ v-for="locale in availableLocales"
+ :key="locale.code"
+ :value="locale.code"
+ :selected="locale.isActive"
+ >
+ {{ locale.code }}
+ </option>
+</select>
This approach avoids hydration issues and ensures that the UI updates correctly when the locale changes.
The new strategy
option, introduced in version 1.50.0, provides more flexibility and control over how locale prefixes are handled in your application. Whether you need a clean, non-prefixed URL structure, or prefer to add locale prefixes for all or some languages, the available strategies allow you to customize your URL structure to fit your needs.
prefix_except_default
or prefix_and_default
.prefix
.no_prefix
when you want to rely on browser language detection and avoid cluttering the URL with prefixes.no_prefix
in static generation mode and use named routes with localeRoute
for better route resolution.<select>
or other approaches to avoid hydration mismatches when rendering locale-dependent content.By understanding and applying these strategies and best practices, you can ensure that your application's localization behavior fits your project's requirements while avoiding common pitfalls.
`,68)]))}const u=s(n,[["render",l]]);export{g as __pageData,u as default}; diff --git a/assets/guide_strategy.md.CUuNsgYn.lean.js b/assets/guide_strategy.md.CUuNsgYn.lean.js new file mode 100644 index 00000000..c263741a --- /dev/null +++ b/assets/guide_strategy.md.CUuNsgYn.lean.js @@ -0,0 +1,26 @@ +import{_ as s,c as i,a2 as a,o as t}from"./chunks/framework.Gfs4HC1t.js";const g=JSON.parse('{"title":"🗂️ Strategies for Locale Prefix Handling in Nuxt I18n (Version 1.50.0+)","description":"","frontmatter":{},"headers":[],"relativePath":"guide/strategy.md","filePath":"guide/strategy.md","lastUpdated":1737355375000}'),n={name:"guide/strategy.md"};function l(o,e,r,h,p,d){return t(),i("div",null,e[0]||(e[0]=[a(`Nuxt I18n
(Version 1.50.0+) Starting with version 1.50.0, Nuxt I18n
introduces a more flexible way to manage how locale prefixes are handled in URLs through the strategy
option. This new approach replaces the deprecated includeDefaultLocaleRoute
and gives you better control over how localization is applied to different routes in your application.
The strategy
option allows you to choose between different behaviors regarding locale prefixes, providing more fine-grained control over the URLs of your application and how they are structured based on the user's selected language.
strategy
(New in Version 1.50.0) The strategy
option defines how locale prefixes should be managed across your routes. The available strategies give you varying levels of control over how the locale appears in the URLs.
Type: string
Default: prefix_and_default
This strategy ensures that no locale prefix is added to your routes. Instead of modifying the URL, the application will detect and change the locale based on the user's browser settings or cookies.
Default Locale: You can set the default locale using an environment variable. For example:
DEFAULT_LOCALE=de npm run dev
DEFAULT_LOCALE=de npm run build
Use Case: Ideal when you want a cleaner URL structure and are relying on automatic language detection rather than explicit locale identifiers in the URL.
i18n: {
+ strategy: 'no_prefix'
+}
Example Routes:
/about
(for any language, e.g., en
, ru
, fr
, etc.)/contact
(for any language)/other
(for any language)/other2
(for any language)With this strategy, all of your routes will include a locale prefix, except for the default language. For the default language, the route will appear without any prefix.
Use Case: Useful when you want all non-default languages to have a distinct URL structure with a locale prefix but prefer the default language to be accessible without the prefix.
i18n: {
+ strategy: 'prefix_except_default'
+}
Example Routes:
/about
(for the default language, e.g., en
)/ru/about
(for Russian)/fr/about
(for French)This strategy ensures that every route in your application will include a locale prefix, regardless of the language. It standardizes the URL structure across all languages.
Use Case: Ideal for situations where you want a consistent URL structure for all languages, ensuring every route includes the locale prefix.
i18n: {
+ strategy: 'prefix'
+}
Example Routes:
/en/about
(for English)/ru/about
(for Russian)/fr/about
(for French)This strategy combines both the prefix
and prefix_except_default
behaviors. It ensures that all languages have a locale prefix in their URLs, but the default language also has a non-prefixed URL version available. When the detectBrowserLanguage
feature is enabled, the prefixed version of the default language will be preferred.
Use Case: Best for applications that want to support both prefixed and non-prefixed URLs for the default language while maintaining a locale prefix for other languages.
i18n: {
+ strategy: 'prefix_and_default'
+}
Example Routes:
/about
(for the default language, e.g., en
)/en/about
(for English, with prefix)/ru/about
(for Russian)/fr/about
(for French)While the strategy
option provides flexibility, there are some known issues and best practices to keep in mind when using these strategies.
no_prefix
Strategy with Static Generation When using the no_prefix
strategy in combination with static site generation (generate
mode), you may encounter a hydration mismatch error. This happens because the locale is determined dynamically (e.g., via cookies or browser settings) after the static page is rendered, leading to a mismatch between the server-rendered content and the client-side hydration.
Error Example:
Hydration completed but contains mismatches.
Workaround:
prefix_except_default
or prefix
if static generation is a requirement.localeRoute
and Route Resolution When using localeRoute
to generate links, there can be issues with route resolution, especially if you rely on path-based routing. For example:
localeRoute('/page') // May cause issues with route resolution
Best Practice:
localeRoute
to avoid unnecessary redirects or route resolution problems:localeRoute({ name: 'page' }) // Preferred approach
This ensures that the correct route is resolved regardless of the locale strategy.
no_prefix
Strategy In the no_prefix
strategy, rendering content that depends on the selected locale (e.g., buttons for switching languages) can lead to issues. For example, if you use a v-for
loop to render locale buttons, Vue may incorrectly apply the disabled
attribute due to hydration mismatches.
Example Problematic Code:
<button
+ v-for="locale in availableLocales"
+ :key="locale.code"
+ :disabled="locale.isActive"
+ :class="{ disabled: locale.isActive }"
+ @click="() => $switchLocale(locale.code)"
+>
+ Switch to {{ locale.code }}
+</button>
Issue:
disabled
attribute during hydration, and it may not update correctly when the locale changes.Best Practice:
<select>
element or another approach that avoids direct DOM manipulation for locale-dependent content:<select @change="(e) => $switchLocale(e.target.value)">
+ <option
+ v-for="locale in availableLocales"
+ :key="locale.code"
+ :value="locale.code"
+ :selected="locale.isActive"
+ >
+ {{ locale.code }}
+ </option>
+</select>
This approach avoids hydration issues and ensures that the UI updates correctly when the locale changes.
The new strategy
option, introduced in version 1.50.0, provides more flexibility and control over how locale prefixes are handled in your application. Whether you need a clean, non-prefixed URL structure, or prefer to add locale prefixes for all or some languages, the available strategies allow you to customize your URL structure to fit your needs.
prefix_except_default
or prefix_and_default
.prefix
.no_prefix
when you want to rely on browser language detection and avoid cluttering the URL with prefixes.no_prefix
in static generation mode and use named routes with localeRoute
for better route resolution.<select>
or other approaches to avoid hydration mismatches when rendering locale-dependent content.By understanding and applying these strategies and best practices, you can ensure that your application's localization behavior fits your project's requirements while avoiding common pitfalls.
`,68)]))}const u=s(n,[["render",l]]);export{g as __pageData,u as default}; diff --git a/assets/guide_testing.md.BhPNxZf_.js b/assets/guide_testing.md.BhPNxZf_.js new file mode 100644 index 00000000..6330e58e --- /dev/null +++ b/assets/guide_testing.md.BhPNxZf_.js @@ -0,0 +1,104 @@ +import{_ as i,c as a,a2 as t,o as n}from"./chunks/framework.Gfs4HC1t.js";const o=JSON.parse('{"title":"🧪 Testing Nuxt I18n Micro Module","description":"","frontmatter":{"outline":"deep"},"headers":[],"relativePath":"guide/testing.md","filePath":"guide/testing.md","lastUpdated":1733313494000}'),e={name:"guide/testing.md"};function l(h,s,p,k,r,E){return n(),a("div",null,s[0]||(s[0]=[t(`Nuxt I18n Micro
Module Testing the Nuxt I18n Micro
module is crucial to ensure that your application's localization features work as expected. This documentation will guide you through setting up the testing environment, creating mock configurations for vitest, and writing tests for your components. For a practical example, you can refer to the example project on GitHub.
nuxt-i18n-micro-test-utils
First, you need to install the testing utilities for Nuxt I18n Micro
. This package provides the necessary tools to mock and test your i18n configurations.
npm install nuxt-i18n-micro-test-utils --save-dev
Next, create a file to set up the mock i18n configuration. This file will be used to mock the i18n functions and utilities during your tests.
// tests/unit-setup.ts
+
+import { mockNuxtImport } from '@nuxt/test-utils/runtime'
+import { vi } from 'vitest'
+import { i18nUtils } from 'nuxt-i18n-micro-test-utils'
+
+export function createFakeI18n() {
+ return {
+ $getLocale: vi.fn(i18nUtils.getLocale),
+ $t: vi.fn(i18nUtils.t),
+ $tc: vi.fn(i18nUtils.tc),
+ $setLocale: vi.fn(i18nUtils.setLocale),
+ $getLocaleName: vi.fn(i18nUtils.getLocaleName),
+ $setLocaleName: vi.fn(i18nUtils.setLocaleName),
+ $getLocales: vi.fn(i18nUtils.getLocales),
+ $setLocales: vi.fn(i18nUtils.setLocales),
+ $defaultLocale: vi.fn(i18nUtils.defaultLocale),
+ $setDefaultLocale: vi.fn(i18nUtils.setDefaultLocale),
+ $getRouteName: vi.fn(i18nUtils.getRouteName),
+ $settRouteName: vi.fn(i18nUtils.settRouteName),
+ $ts: vi.fn(i18nUtils.ts),
+ $tn: vi.fn(i18nUtils.tn),
+ $td: vi.fn(i18nUtils.td),
+ $has: vi.fn(i18nUtils.has),
+ $mergeTranslations: vi.fn(i18nUtils.mergeTranslations),
+ $switchLocaleRoute: vi.fn(i18nUtils.switchLocaleRoute),
+ $switchLocalePath: vi.fn(i18nUtils.switchLocalePath),
+ $switchLocale: vi.fn(i18nUtils.switchLocale),
+ $switchRoute: vi.fn(i18nUtils.switchRoute),
+ $localeRoute: vi.fn(i18nUtils.localeRoute),
+ $localePath: vi.fn(i18nUtils.localePath),
+ $setI18nRouteParams: vi.fn(i18nUtils.setI18nRouteParams),
+ }
+}
+
+mockNuxtImport<() => ReturnType<typeof createFakeI18n>>('useI18n', () =>
+ vi.fn(() => createFakeI18n()),
+)
+
+export const setTranslationsFromJson = i18nUtils.setTranslationsFromJson
Now, configure Vitest to use the mock configuration file and set up the testing environment.
// vitest.config.ts
+
+import { defineVitestConfig } from '@nuxt/test-utils/config'
+
+export default defineVitestConfig({
+ test: {
+ watch: false,
+ setupFiles: ['./tests/unit-setup.ts'],
+ include: ['./**/*.spec.ts'],
+ },
+})
Here’s an example of a simple component that uses the useI18n
composable to translate messages.
<script setup lang="ts">
+const { $t } = useI18n()
+
+const props = defineProps({
+ message: {
+ type: String,
+ default: null,
+ },
+})
+
+// Test to see that $t works in script setup as well as the template
+const message = props.message || $t('defaultMessage')
+</script>
+
+<template>
+ <div>
+ <p>Test from component: {{ $t('welcome') }}</p>
+ <p data-testid="message">
+ Test message from props: {{ message }}
+ </p>
+ </div>
+</template>
Now, let’s write a test for this component.
// tests/unit/example.spec.ts
+
+import { describe, it, expect, beforeEach } from 'vitest'
+import { mount } from '@vue/test-utils'
+import ExampleComponent from '@/components/ExampleComponent.vue'
+import fs from 'fs'
+import path from 'path'
+import { setTranslationsFromJson } from './unit-setup'
+
+describe('ExampleComponent', () => {
+ beforeEach(async () => {
+ const fileContent = fs.readFileSync(path.join(__dirname, '../../locales/en-GB.json')).toString()
+ await setTranslationsFromJson('en', JSON.parse(fileContent))
+ })
+
+ it('renders the welcome message correctly', () => {
+ const wrapper = mount(ExampleComponent)
+ expect(wrapper.text()).toContain('Test from component: Welcome')
+ })
+
+ it('renders the default message correctly', () => {
+ const wrapper = mount(ExampleComponent)
+ expect(wrapper.find('[data-testid="message"]').text()).toContain('Test message from props: Default Message')
+ })
+
+ it('renders the custom message correctly', () => {
+ const wrapper = mount(ExampleComponent, {
+ props: {
+ message: 'Custom Message',
+ },
+ })
+ expect(wrapper.find('[data-testid="message"]').text()).toContain('Test message from props: Custom Message')
+ })
+})
nuxt-i18n-micro-test-utils
to ensure consistent and predictable test results.Below is a table describing all the utility methods provided by nuxt-i18n-micro-test-utils
.
Method | Description |
---|---|
t(key, params, defaultValue) | Translates a key with optional parameters and a default value. |
tc(key, params, defaultValue) | Translates a key with pluralization support. |
setTranslationsFromJson(locale, translations) | Loads translations from a JSON object for a specific locale. |
getLocale() | Returns the current locale. |
setLocale(val) | Sets the current locale. |
getLocaleName() | Returns the current locale name. |
setLocaleName(val) | Sets the current locale name. |
getLocales() | Returns the list of available locales. |
setLocales(val) | Sets the list of available locales. |
defaultLocale() | Returns the default locale. |
setDefaultLocale(val) | Sets the default locale. |
getRouteName() | Returns the current route name. |
settRouteName(val) | Sets the current route name. |
ts(key, params, defaultValue) | Translates a key and returns the result as a string. |
tn(value, options) | Formats a number according to the current locale. |
td(value, options) | Formats a date according to the current locale. |
has(key) | Checks if a translation key exists. |
By following these steps, you can effectively test the Nuxt I18n Micro
module and ensure that your application's localization features work as expected.
Nuxt I18n Micro
Module Testing the Nuxt I18n Micro
module is crucial to ensure that your application's localization features work as expected. This documentation will guide you through setting up the testing environment, creating mock configurations for vitest, and writing tests for your components. For a practical example, you can refer to the example project on GitHub.
nuxt-i18n-micro-test-utils
First, you need to install the testing utilities for Nuxt I18n Micro
. This package provides the necessary tools to mock and test your i18n configurations.
npm install nuxt-i18n-micro-test-utils --save-dev
Next, create a file to set up the mock i18n configuration. This file will be used to mock the i18n functions and utilities during your tests.
// tests/unit-setup.ts
+
+import { mockNuxtImport } from '@nuxt/test-utils/runtime'
+import { vi } from 'vitest'
+import { i18nUtils } from 'nuxt-i18n-micro-test-utils'
+
+export function createFakeI18n() {
+ return {
+ $getLocale: vi.fn(i18nUtils.getLocale),
+ $t: vi.fn(i18nUtils.t),
+ $tc: vi.fn(i18nUtils.tc),
+ $setLocale: vi.fn(i18nUtils.setLocale),
+ $getLocaleName: vi.fn(i18nUtils.getLocaleName),
+ $setLocaleName: vi.fn(i18nUtils.setLocaleName),
+ $getLocales: vi.fn(i18nUtils.getLocales),
+ $setLocales: vi.fn(i18nUtils.setLocales),
+ $defaultLocale: vi.fn(i18nUtils.defaultLocale),
+ $setDefaultLocale: vi.fn(i18nUtils.setDefaultLocale),
+ $getRouteName: vi.fn(i18nUtils.getRouteName),
+ $settRouteName: vi.fn(i18nUtils.settRouteName),
+ $ts: vi.fn(i18nUtils.ts),
+ $tn: vi.fn(i18nUtils.tn),
+ $td: vi.fn(i18nUtils.td),
+ $has: vi.fn(i18nUtils.has),
+ $mergeTranslations: vi.fn(i18nUtils.mergeTranslations),
+ $switchLocaleRoute: vi.fn(i18nUtils.switchLocaleRoute),
+ $switchLocalePath: vi.fn(i18nUtils.switchLocalePath),
+ $switchLocale: vi.fn(i18nUtils.switchLocale),
+ $switchRoute: vi.fn(i18nUtils.switchRoute),
+ $localeRoute: vi.fn(i18nUtils.localeRoute),
+ $localePath: vi.fn(i18nUtils.localePath),
+ $setI18nRouteParams: vi.fn(i18nUtils.setI18nRouteParams),
+ }
+}
+
+mockNuxtImport<() => ReturnType<typeof createFakeI18n>>('useI18n', () =>
+ vi.fn(() => createFakeI18n()),
+)
+
+export const setTranslationsFromJson = i18nUtils.setTranslationsFromJson
Now, configure Vitest to use the mock configuration file and set up the testing environment.
// vitest.config.ts
+
+import { defineVitestConfig } from '@nuxt/test-utils/config'
+
+export default defineVitestConfig({
+ test: {
+ watch: false,
+ setupFiles: ['./tests/unit-setup.ts'],
+ include: ['./**/*.spec.ts'],
+ },
+})
Here’s an example of a simple component that uses the useI18n
composable to translate messages.
<script setup lang="ts">
+const { $t } = useI18n()
+
+const props = defineProps({
+ message: {
+ type: String,
+ default: null,
+ },
+})
+
+// Test to see that $t works in script setup as well as the template
+const message = props.message || $t('defaultMessage')
+</script>
+
+<template>
+ <div>
+ <p>Test from component: {{ $t('welcome') }}</p>
+ <p data-testid="message">
+ Test message from props: {{ message }}
+ </p>
+ </div>
+</template>
Now, let’s write a test for this component.
// tests/unit/example.spec.ts
+
+import { describe, it, expect, beforeEach } from 'vitest'
+import { mount } from '@vue/test-utils'
+import ExampleComponent from '@/components/ExampleComponent.vue'
+import fs from 'fs'
+import path from 'path'
+import { setTranslationsFromJson } from './unit-setup'
+
+describe('ExampleComponent', () => {
+ beforeEach(async () => {
+ const fileContent = fs.readFileSync(path.join(__dirname, '../../locales/en-GB.json')).toString()
+ await setTranslationsFromJson('en', JSON.parse(fileContent))
+ })
+
+ it('renders the welcome message correctly', () => {
+ const wrapper = mount(ExampleComponent)
+ expect(wrapper.text()).toContain('Test from component: Welcome')
+ })
+
+ it('renders the default message correctly', () => {
+ const wrapper = mount(ExampleComponent)
+ expect(wrapper.find('[data-testid="message"]').text()).toContain('Test message from props: Default Message')
+ })
+
+ it('renders the custom message correctly', () => {
+ const wrapper = mount(ExampleComponent, {
+ props: {
+ message: 'Custom Message',
+ },
+ })
+ expect(wrapper.find('[data-testid="message"]').text()).toContain('Test message from props: Custom Message')
+ })
+})
nuxt-i18n-micro-test-utils
to ensure consistent and predictable test results.Below is a table describing all the utility methods provided by nuxt-i18n-micro-test-utils
.
Method | Description |
---|---|
t(key, params, defaultValue) | Translates a key with optional parameters and a default value. |
tc(key, params, defaultValue) | Translates a key with pluralization support. |
setTranslationsFromJson(locale, translations) | Loads translations from a JSON object for a specific locale. |
getLocale() | Returns the current locale. |
setLocale(val) | Sets the current locale. |
getLocaleName() | Returns the current locale name. |
setLocaleName(val) | Sets the current locale name. |
getLocales() | Returns the list of available locales. |
setLocales(val) | Sets the list of available locales. |
defaultLocale() | Returns the default locale. |
setDefaultLocale(val) | Sets the default locale. |
getRouteName() | Returns the current route name. |
settRouteName(val) | Sets the current route name. |
ts(key, params, defaultValue) | Translates a key and returns the result as a string. |
tn(value, options) | Formats a number according to the current locale. |
td(value, options) | Formats a date according to the current locale. |
has(key) | Checks if a translation key exists. |
By following these steps, you can effectively test the Nuxt I18n Micro
module and ensure that your application's localization features work as expected.
Nuxt I18n Micro
is a fast, simple, and lightweight internationalization (i18n) module for Nuxt. Despite its compact size, it's designed with large projects in mind, offering significant performance improvements over traditional i18n solutions like nuxt-i18n
. The module was built from the ground up to be highly efficient, focusing on minimizing build times, reducing server load, and shrinking bundle sizes.
The Nuxt I18n Micro
module was created to address critical performance issues found in the original nuxt-i18n
module, particularly in high-traffic environments and projects with large translation files. Key issues with nuxt-i18n
include:
To showcase the efficiency of Nuxt I18n Micro
, we conducted tests under identical conditions. Both modules were tested with a 10MB translation file on the same hardware.
Nuxt I18n Micro
Nuxt I18n Micro
These results clearly demonstrate that Nuxt I18n Micro
significantly outperforms the original module in every critical area.
Nuxt I18n Micro
is designed for large-scale projects, focusing on performance and efficiency.dev
mode if not present.Install the module in your Nuxt application with:
npm install nuxt-i18n-micro
Then, add it to your nuxt.config.ts
:
export default defineNuxtConfig({
+ modules: [
+ 'nuxt-i18n-micro',
+ ],
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-US', dir: 'ltr' },
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr' },
+ { code: 'ar', iso: 'ar-SA', dir: 'rtl' },
+ ],
+ defaultLocale: 'en',
+ translationDir: 'locales',
+ meta: true,
+ },
+})
That's it! You're now ready to use Nuxt I18n Micro in your Nuxt app.
Translations are organized into global and page-specific files:
/locales
+ ├── /pages
+ │ ├── /index
+ │ │ ├── en.json
+ │ │ ├── fr.json
+ │ │ └── ar.json
+ │ ├── /about
+ │ │ ├── en.json
+ │ │ ├── fr.json
+ │ │ └── ar.json
+ ├── en.json
+ ├── fr.json
+ └── ar.json
Nuxt I18n Micro
is a fast, simple, and lightweight internationalization (i18n) module for Nuxt. Despite its compact size, it's designed with large projects in mind, offering significant performance improvements over traditional i18n solutions like nuxt-i18n
. The module was built from the ground up to be highly efficient, focusing on minimizing build times, reducing server load, and shrinking bundle sizes.
The Nuxt I18n Micro
module was created to address critical performance issues found in the original nuxt-i18n
module, particularly in high-traffic environments and projects with large translation files. Key issues with nuxt-i18n
include:
To showcase the efficiency of Nuxt I18n Micro
, we conducted tests under identical conditions. Both modules were tested with a 10MB translation file on the same hardware.
Nuxt I18n Micro
Nuxt I18n Micro
These results clearly demonstrate that Nuxt I18n Micro
significantly outperforms the original module in every critical area.
Nuxt I18n Micro
is designed for large-scale projects, focusing on performance and efficiency.dev
mode if not present.Install the module in your Nuxt application with:
npm install nuxt-i18n-micro
Then, add it to your nuxt.config.ts
:
export default defineNuxtConfig({
+ modules: [
+ 'nuxt-i18n-micro',
+ ],
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-US', dir: 'ltr' },
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr' },
+ { code: 'ar', iso: 'ar-SA', dir: 'rtl' },
+ ],
+ defaultLocale: 'en',
+ translationDir: 'locales',
+ meta: true,
+ },
+})
That's it! You're now ready to use Nuxt I18n Micro in your Nuxt app.
Translations are organized into global and page-specific files:
/locales
+ ├── /pages
+ │ ├── /index
+ │ │ ├── en.json
+ │ │ ├── fr.json
+ │ │ └── ar.json
+ │ ├── /about
+ │ │ ├── en.json
+ │ │ ├── fr.json
+ │ │ └── ar.json
+ ├── en.json
+ ├── fr.json
+ └── ar.json
Date: 2025-01-20
Version: v1.65.0
We’re thrilled to announce v1.65.0, featuring a complete rewrite of core logic for better performance and maintainability! This release includes enhanced TypeScript support, client-side locale redirection, and streamlined translation handling. Upgrade now for a smoother, faster experience! 🚀
Date: 2025-01-10
Version Introduced: v1.58.0
We are thrilled to announce the release of a new algorithm for loading translations in Nuxt I18n Micro. This update introduces significant performance improvements, a cleaner architecture, and more efficient memory usage.
The new translation-loading algorithm focuses on:
The new algorithm reduces build times by efficiently handling translation files and minimizing memory overhead.
Lower maximum and average CPU usage during builds and stress tests:
Memory consumption has been significantly optimized across builds and runtime stress tests:
Stress test response times saw drastic improvement:
The new algorithm boosts the number of handled requests per second:
Localization is essential for global applications, and improving translation-loading performance can have a direct impact on:
text-to-i18n
Date: 2024-12-24
Cli Version Introduced: v1.1.0
We’re excited to announce the new text-to-i18n
command in the Nuxt I18n Micro CLI! This powerful feature automates the process of extracting hardcoded text strings from your codebase and converting them into i18n translation keys. It’s designed to save time, reduce errors, and streamline your localization workflow.
pages
, components
, and plugins
.i18n-micro text-to-i18n [options]
Example:
i18n-micro text-to-i18n --translationFile locales/en.json --context auth
<template>
+ <div>
+ <h1>Welcome to our site</h1>
+ <p>Please sign in to continue</p>
+ </div>
+</template>
<template>
+ <div>
+ <h1>{{ $t('pages.home.welcome_to_our_site') }}</h1>
+ <p>{{ $t('pages.home.please_sign_in') }}</p>
+ </div>
+</template>
For more details, check out the documentation.
Date: 2025-01-20
Version: v1.65.0
We’re thrilled to announce v1.65.0, featuring a complete rewrite of core logic for better performance and maintainability! This release includes enhanced TypeScript support, client-side locale redirection, and streamlined translation handling. Upgrade now for a smoother, faster experience! 🚀
Date: 2025-01-10
Version Introduced: v1.58.0
We are thrilled to announce the release of a new algorithm for loading translations in Nuxt I18n Micro. This update introduces significant performance improvements, a cleaner architecture, and more efficient memory usage.
The new translation-loading algorithm focuses on:
The new algorithm reduces build times by efficiently handling translation files and minimizing memory overhead.
Lower maximum and average CPU usage during builds and stress tests:
Memory consumption has been significantly optimized across builds and runtime stress tests:
Stress test response times saw drastic improvement:
The new algorithm boosts the number of handled requests per second:
Localization is essential for global applications, and improving translation-loading performance can have a direct impact on:
text-to-i18n
Date: 2024-12-24
Cli Version Introduced: v1.1.0
We’re excited to announce the new text-to-i18n
command in the Nuxt I18n Micro CLI! This powerful feature automates the process of extracting hardcoded text strings from your codebase and converting them into i18n translation keys. It’s designed to save time, reduce errors, and streamline your localization workflow.
pages
, components
, and plugins
.i18n-micro text-to-i18n [options]
Example:
i18n-micro text-to-i18n --translationFile locales/en.json --context auth
<template>
+ <div>
+ <h1>Welcome to our site</h1>
+ <p>Please sign in to continue</p>
+ </div>
+</template>
<template>
+ <div>
+ <h1>{{ $t('pages.home.welcome_to_our_site') }}</h1>
+ <p>{{ $t('pages.home.please_sign_in') }}</p>
+ </div>
+</template>
For more details, check out the documentation.
This section provides various examples demonstrating how to use Nuxt I18n Micro
in your Nuxt.js application. You'll see how to switch locales, use the <i18n-link>
, <i18n-switcher>
, and <i18n-t>
components, and dynamically handle translation keys.
Here's a basic setup to get started with Nuxt I18n Micro
:
export default defineNuxtConfig({
+ modules: ['nuxt-i18n-micro'],
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-US', dir: 'ltr', disabled: false, displayName: 'English' },
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr', disabled: false, displayName: 'Français' },
+ { code: 'de', iso: 'de-DE', dir: 'ltr', disabled: false, displayName: 'Deutsch' },
+ ],
+ defaultLocale: 'en',
+ translationDir: 'locales',
+ meta: true,
+ },
+})
This example demonstrates how to switch locales programmatically using buttons:
<template>
+ <div>
+ <p>Current Locale: {{ $getLocale() }}</p>
+ <div>
+ <button
+ v-for="locale in $getLocales()"
+ :key="locale.code"
+ :disabled="locale.code === $getLocale()"
+ @click="() => $switchLocale(locale.code)"
+ >
+ Switch to {{ $t(locale.code) }}
+ </button>
+ </div>
+ </div>
+</template>
+
+<script setup>
+import { useNuxtApp } from '#imports'
+
+const { $getLocale, $switchLocale, $getLocales, $t } = useNuxtApp()
+</script>
{
+ "en": "English",
+ "fr": "Français",
+ "de": "Deutsch"
+}
<i18n-switcher>
Component The <i18n-switcher>
component provides a dropdown for locale switching with customizable labels:
<template>
+ <div>
+ <i18n-switcher
+ :custom-labels="{ en: 'English', fr: 'Français', de: 'Deutsch' }"
+ />
+ </div>
+</template>
<i18n-link>
for Localized Navigation The <i18n-link>
component automatically handles locale-specific routing:
<template>
+ <div>
+ <i18n-link to="/about">{{ $t('about') }}</i18n-link>
+ <i18n-link :to="{ name: 'index' }">{{ $t('home') }}</i18n-link>
+ </div>
+</template>
+
+<script setup>
+ import { useNuxtApp } from '#imports'
+
+ const { $getLocale, $switchLocale, $getLocales, $t } = useNuxtApp()
+</script>
{
+ "about": "About Us",
+ "home": "Home"
+}
<template>
+ <div>
+ <i18n-link to="/about" activeClass="current">About Us</i18n-link>
+ </div>
+</template>
The same JSON file can be used as in the previous example for this scenario.
In some scenarios, you may want to iterate over dynamic keys stored within your translation files and render their values conditionally. The example below demonstrates how to achieve this using Nuxt I18n Micro
.
This example fetches an array of keys from a specific translation path (in this case, dynamic
) and iterates over them. Each key is checked for its existence using $has
before rendering its value with $t
.
<template>
+ <div>
+ <div
+ v-for="key in $t('dynamic')"
+ :key="key"
+ >
+ <p>{{ key }}: <span v-if="$has(key)">{{ $t(key) }}</span></p>
+ </div>
+ </div>
+</template>
+
+<script setup>
+import { useNuxtApp } from '#imports'
+
+const { $t, $has } = useNuxtApp()
+</script>
en.json
) {
+ "dynamic": ["key1", "key2", "key3"],
+ "key1": "This is the first key's value",
+ "key2": "This is the second key's value",
+ "key3": "This is the third key's value"
+}
In this example, we handle an object stored within your translation file. We fetch and iterate over the keys of the object, dynamically rendering both the key names and their associated values.
<template>
+ <div>
+ <div v-for="(value, key) in $t('dynamicObject')" :key="key">
+ <p>{{ key }}: {{ value }}</p>
+ </div>
+ </div>
+</template>
+
+<script setup>
+import { useNuxtApp } from '#imports'
+
+const { $t } = useNuxtApp()
+</script>
en.json
) {
+ "dynamicObject": {
+ "title": "Welcome to our site",
+ "description": "This is a brief description of our services.",
+ "footerNote": "Thank you for visiting!"
+ }
+}
<i18n-t>
for Translations with Slots and Interpolation The <i18n-t>
component is useful for rendering translations with dynamic content and HTML tags:
<template>
+ <i18n-t keypath="greeting" tag="h1">
+ <template #default="{ translation }">
+ <strong>{{ translation.replace('page', 'page replace') }}</strong> <i>!!!</i>
+ </template>
+ </i18n-t>
+</template>
<i18n-t>
{
+ "greeting": "Welcome to the page"
+}
<template>
+ <i18n-t keypath="welcome" :params="{ username: 'Alice', unreadCount: 5 }"></i18n-t>
+</template>
{
+ "welcome": "Hello {username}, you have {unreadCount} unread messages."
+}
Here's a complex structure demonstrating multiple translation uses within a single page:
<template>
+ <div>
+ <h1>{{ $t('mainHeader') }}</h1>
+
+ <nav>
+ <ul>
+ <li><a href="#">{{ $t('nav.home') }}</a></li>
+ <li><a href="#">{{ $t('nav.about') }}</a></li>
+ <li><a href="#">{{ $t('nav.services') }}</a></li>
+ <li><a href="#">{{ $t('nav.contact') }}</a></li>
+ </ul>
+ </nav>
+
+ <section>
+ <h2>{{ $t('section1.header') }}</h2>
+ <p>{{ $t('section1.intro') }}</p>
+
+ <div>
+ <h3>{{ $t('section1.subsection1.header') }}</h3>
+ <p>{{ $t('section1.subsection1.content') }}</p>
+ </div>
+
+ <div>
+ <h3>{{ $t('section1.subsection2.header') }}</h3>
+ <ul>
+ <li>{{ $t('section1.subsection2.item1') }}</li>
+ <li>{{ $t('section1.subsection2.item2') }}</li>
+ <li>{{ $t('section1.subsection2.item3') }}</li>
+ </ul>
+ </div>
+ </section>
+
+ <footer>
+ <h4>{{ $t('footer.contact.header') }}</h4>
+ <address>
+ {{ $t('footer.contact.address') }}<br>
+ {{ $t('footer.contact.city') }}<br>
+ {{ $t('footer.contact.phone') }}
+ </address>
+ </footer>
+
+ <div>
+ <button
+ v-for="locale in $getLocales()"
+ :key="locale.code"
+ :disabled="locale.code === $getLocale()"
+ @click="() => $switchLocale(locale.code)"
+ >
+ Switch to {{ locale.code }}
+ </button>
+ </div>
+ </div>
+</template>
+
+<script setup>
+import { useNuxtApp } from '#imports'
+
+const { $getLocale, $switchLocale, $getLocales, $t } = useNuxtApp()
+</script>
{
+ "mainHeader": "Welcome to Our Services",
+ "nav": {
+ "home": "Home",
+ "about": "About Us",
+ "services": "Services",
+ "contact": "Contact"
+ },
+ "section1": {
+ "header": "Our Expertise",
+ "intro": "We provide a wide range of services to meet your needs.",
+ "subsection1": {
+ "header": "Consulting",
+ "content": "Our team offers expert consulting services in various domains."
+ },
+ "subsection2": {
+ "header": "Development",
+ "item1":
+
+ "Web Development",
+ "item2": "Mobile Apps",
+ "item3": "Custom Software"
+ }
+ },
+ "footer": {
+ "contact": {
+ "header": "Contact Us",
+ "address": "123 Main Street",
+ "city": "Anytown, USA",
+ "phone": "+1 (555) 123-4567"
+ }
+ }
+}
$tc
for Pluralization The $tc
function in Nuxt I18n Micro
handles pluralization based on the count and locale settings. This is useful for dynamically adjusting messages that involve counts, such as items, notifications, or other entities that can vary in number.
$tc
for Pluralization In the following example, we display a message indicating the number of apples using $tc
. The translation key handles multiple plural forms based on the count provided.
<template>
+ <div>
+ <!-- Display a pluralized message about the number of apples -->
+ <p>{{ $tc('apples', 0) }}</p> <!-- Outputs: no apples -->
+ <p>{{ $tc('apples', 1) }}</p> <!-- Outputs: one apple -->
+ <p>{{ $tc('apples', 10) }}</p> <!-- Outputs: 10 apples -->
+ </div>
+</template>
+
+<script setup>
+import { useNuxtApp } from '#imports'
+
+const { $tc } = useNuxtApp()
+</script>
Here's how you can define the translation in your JSON file to handle different plural forms:
{
+ "apples": "no apples | one apple | {count} apples"
+}
$tc('apples', 0)
: Returns the first form, used when the count is zero ("no apples"
).$tc('apples', 1)
: Returns the second form, used when the count is one ("one apple"
).$tc('apples', 10)
: Returns the third form with the count value, used when the count is two or more ("10 apples"
).If your application needs to handle more complex pluralization rules (e.g., specific cases for zero, one, two, few, many, other), you can extend the translation strings accordingly:
{
+ "apples": "no apples | one apple | two apples | a few apples | many apples | {count} apples"
+}
$tc('apples', 2)
: Could be set up to return "two apples"
.$tc('apples', 3)
: Could return "a few apples"
, depending on the rules defined for the count.$tn
for Number Formatting The $tn
function formats numbers according to the current locale using the Intl.NumberFormat
API. This is useful for displaying numbers in a way that matches the user's regional settings, such as currency, percentages, or other number formats.
$tn
for Number Formatting <template>
+ <div>
+ <!-- Format a number as currency -->
+ <p>{{ $tn(1234567.89, { style: 'currency', currency: 'USD' }) }}</p> <!-- Outputs: $1,234,567.89 in 'en-US' locale -->
+
+ <!-- Format a number with custom options -->
+ <p>{{ $tn(0.567, { style: 'percent', minimumFractionDigits: 1 }) }}</p> <!-- Outputs: 56.7% in 'en-US' locale -->
+ </div>
+</template>
+
+<script setup>
+import { useNuxtApp } from '#imports'
+
+const { $tn } = useNuxtApp()
+</script>
$td
for Date and Time Formatting The $td
function formats dates and times according to the current locale using the Intl.DateTimeFormat
API. This is useful for displaying dates and times in formats that are familiar to the user based on their locale settings.
$td
for Date and Time Formatting <template>
+ <div>
+ <!-- Format a date with full options -->
+ <p>{{ $td(new Date(), { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }) }}</p> <!-- Outputs: "Friday, September 1, 2023" in 'en-US' locale -->
+
+ <!-- Format a date with time -->
+ <p>{{ $td(new Date(), { hour: '2-digit', minute: '2-digit', second: '2-digit' }) }}</p> <!-- Outputs: "10:15:30 AM" in 'en-US' locale -->
+ </div>
+</template>
+
+<script setup>
+import { useNuxtApp } from '#imports'
+
+const { $td } = useNuxtApp()
+</script>
$tdr
for Relative Date Formatting The $tdr
function formats dates as relative times (e.g., "5 minutes ago", "2 days ago") according to the current locale using the Intl.RelativeTimeFormat
API. This is useful for displaying time differences relative to the current date and time.
$tdr
for Relative Date Formatting <template>
+ <div>
+ <!-- Format a date as a relative time -->
+ <p>{{ $tdr(new Date(Date.now() - 1000 * 60 * 5)) }}</p> <!-- Outputs: "5 minutes ago" in 'en-US' locale -->
+
+ <!-- Format a date that is in the future -->
+ <p>{{ $tdr(new Date(Date.now() + 1000 * 60 * 60 * 24)) }}</p> <!-- Outputs: "in 1 day" in 'en-US' locale -->
+ </div>
+</template>
+
+<script setup>
+import { useNuxtApp } from '#imports'
+
+const { $tdr } = useNuxtApp()
+</script>
Fast, Simple, and Lightweight Internationalization for Nuxt
Optimize your Nuxt app with a powerful and efficient i18n solution.
Nuxt I18n Micro
is a fast, simple, and lightweight internationalization (i18n) module for Nuxt. Despite its compact size, it's designed with large projects in mind, offering significant performance improvements over traditional i18n solutions like nuxt-i18n
. The module was built from the ground up to be highly efficient, focusing on minimizing build times, reducing server load, and shrinking bundle sizes.
The Nuxt I18n Micro
module was created to address critical performance issues found in the original nuxt-i18n
module, particularly in high-traffic environments and projects with large translation files. Key issues with nuxt-i18n
include:
To showcase the efficiency of Nuxt I18n Micro
, we conducted tests under identical conditions. Both modules were tested with a 10MB translation file on the same hardware.
Nuxt I18n Micro
Nuxt I18n Micro
These results clearly demonstrate that Nuxt I18n Micro
significantly outperforms the original module in every critical area.
Nuxt I18n Micro
is designed for large-scale projects, focusing on performance and efficiency.dev
mode if not present.Install the module in your Nuxt application with:
npm install nuxt-i18n-micro
Then, add it to your nuxt.config.ts
:
export default defineNuxtConfig({
+ modules: [
+ 'nuxt-i18n-micro',
+ ],
+ i18n: {
+ locales: [
+ { code: 'en', iso: 'en-US', dir: 'ltr' },
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr' },
+ { code: 'ar', iso: 'ar-SA', dir: 'rtl' },
+ ],
+ defaultLocale: 'en',
+ translationDir: 'locales',
+ meta: true,
+ },
+})
That's it! You're now ready to use Nuxt I18n Micro in your Nuxt app.
Translations are organized into global and page-specific files:
/locales
+ ├── /pages
+ │ ├── /index
+ │ │ ├── en.json
+ │ │ ├── fr.json
+ │ │ └── ar.json
+ │ ├── /about
+ │ │ ├── en.json
+ │ │ ├── fr.json
+ │ │ └── ar.json
+ ├── en.json
+ ├── fr.json
+ └── ar.json
Date: 2025-01-20
Version: v1.65.0
We’re thrilled to announce v1.65.0, featuring a complete rewrite of core logic for better performance and maintainability! This release includes enhanced TypeScript support, client-side locale redirection, and streamlined translation handling. Upgrade now for a smoother, faster experience! 🚀
Date: 2025-01-10
Version Introduced: v1.58.0
We are thrilled to announce the release of a new algorithm for loading translations in Nuxt I18n Micro. This update introduces significant performance improvements, a cleaner architecture, and more efficient memory usage.
The new translation-loading algorithm focuses on:
The new algorithm reduces build times by efficiently handling translation files and minimizing memory overhead.
Lower maximum and average CPU usage during builds and stress tests:
Memory consumption has been significantly optimized across builds and runtime stress tests:
Stress test response times saw drastic improvement:
The new algorithm boosts the number of handled requests per second:
Localization is essential for global applications, and improving translation-loading performance can have a direct impact on:
text-to-i18n
Date: 2024-12-24
Cli Version Introduced: v1.1.0
We’re excited to announce the new text-to-i18n
command in the Nuxt I18n Micro CLI! This powerful feature automates the process of extracting hardcoded text strings from your codebase and converting them into i18n translation keys. It’s designed to save time, reduce errors, and streamline your localization workflow.
pages
, components
, and plugins
.i18n-micro text-to-i18n [options]
Example:
i18n-micro text-to-i18n --translationFile locales/en.json --context auth
<template>
+ <div>
+ <h1>Welcome to our site</h1>
+ <p>Please sign in to continue</p>
+ </div>
+</template>
<template>
+ <div>
+ <h1>{{ $t('pages.home.welcome_to_our_site') }}</h1>
+ <p>{{ $t('pages.home.please_sign_in') }}</p>
+ </div>
+</template>
For more details, check out the documentation.