⚡ 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 0000000..e69de29 diff --git a/404.html b/404.html new file mode 100644 index 0000000..35b1c34 --- /dev/null +++ b/404.html @@ -0,0 +1,21 @@ + + +
+ + +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.D1_p7qRJ.lean.js b/assets/api_events.md.D1_p7qRJ.lean.js new file mode 100644 index 0000000..bc29386 --- /dev/null +++ b/assets/api_events.md.D1_p7qRJ.lean.js @@ -0,0 +1,31 @@ +import{_ as s,c as a,a2 as n,o as t}from"./chunks/framework.CBrKbnPu.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.CeANTGTe.js b/assets/api_methods.md.CeANTGTe.js new file mode 100644 index 0000000..a67b873 --- /dev/null +++ b/assets/api_methods.md.CeANTGTe.js @@ -0,0 +1,126 @@ +import{_ as i,c as a,a2 as t,o as n}from"./chunks/framework.CBrKbnPu.js";const g=JSON.parse('{"title":"🛠️ Methods","description":"","frontmatter":{"outline":"deep"},"headers":[],"relativePath":"api/methods.md","filePath":"api/methods.md","lastUpdated":1729695167000}'),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
— The count for pluralization.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
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
$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',
+ },
+})
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.
import { useNuxtApp } from '#imports'
+
+const { $defineI18nRoute } = useNuxtApp()
+
+$defineI18nRoute({
+ locales: ['en', 'fr', 'de'] // Only these locales are allowed for this route
+})
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
+ }
+})
{}
) 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
— The count for pluralization.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
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
$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',
+ },
+})
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.
import { useNuxtApp } from '#imports'
+
+const { $defineI18nRoute } = useNuxtApp()
+
+$defineI18nRoute({
+ locales: ['en', 'fr', 'de'] // Only these locales are allowed for this route
+})
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
+ }
+})
{}
) 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-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>
Here’s the updated documentation for the <i18n-switcher>
component, reflecting the transition to using inline styles with support for dynamic customization through props:
<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>\n <i18n-switcher />\n</template>
This renders a locale switcher with default styling and behavior.
<template>\n <i18n-switcher\n :customLabels="{ en: 'English', fr: 'Français' }"\n :customWrapperStyle="{ backgroundColor: '#f8f9fa', padding: '10px' }"\n :customButtonStyle="{ backgroundColor: '#007bff', color: '#fff', borderRadius: '4px' }"\n :customDropdownStyle="{ border: '1px solid #007bff', boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)' }"\n :customItemStyle="{ margin: '5px 0', padding: '5px' }"\n :customLinkStyle="{ padding: '8px 16px', color: '#333', textDecoration: 'none' }"\n :customActiveLinkStyle="{ color: 'green', fontWeight: 'bold', backgroundColor: '#f0f0f0' }"\n :customDisabledLinkStyle="{ color: 'gray', cursor: 'not-allowed' }"\n :customIconStyle="{ fontSize: '20px', color: '#007bff' }"\n />\n</template>
This example demonstrates a fully customized locale switcher with custom labels and inline styles.
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.
',34)]))}const g=i(e,[["render",n]]);export{d as __pageData,g as default}; diff --git a/assets/components_i18n-switcher.md.CZU12ZBI.lean.js b/assets/components_i18n-switcher.md.CZU12ZBI.lean.js new file mode 100644 index 0000000..f5506da --- /dev/null +++ b/assets/components_i18n-switcher.md.CZU12ZBI.lean.js @@ -0,0 +1 @@ +import{_ as i,c as t,a2 as a,o as l}from"./chunks/framework.CBrKbnPu.js";const d=JSON.parse('{"title":"🌍Here’s the updated documentation for the <i18n-switcher>
component, reflecting the transition to using inline styles with support for dynamic customization through props:
<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>\n <i18n-switcher />\n</template>
This renders a locale switcher with default styling and behavior.
<template>\n <i18n-switcher\n :customLabels="{ en: 'English', fr: 'Français' }"\n :customWrapperStyle="{ backgroundColor: '#f8f9fa', padding: '10px' }"\n :customButtonStyle="{ backgroundColor: '#007bff', color: '#fff', borderRadius: '4px' }"\n :customDropdownStyle="{ border: '1px solid #007bff', boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)' }"\n :customItemStyle="{ margin: '5px 0', padding: '5px' }"\n :customLinkStyle="{ padding: '8px 16px', color: '#333', textDecoration: 'none' }"\n :customActiveLinkStyle="{ color: 'green', fontWeight: 'bold', backgroundColor: '#f0f0f0' }"\n :customDisabledLinkStyle="{ color: 'gray', cursor: 'not-allowed' }"\n :customIconStyle="{ fontSize: '20px', color: '#007bff' }"\n />\n</template>
This example demonstrates a fully customized locale switcher with custom labels and inline styles.
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.
',34)]))}const g=i(e,[["render",n]]);export{d as __pageData,g as default}; diff --git a/assets/components_i18n-t.md.Dn3NUPHA.js b/assets/components_i18n-t.md.Dn3NUPHA.js new file mode 100644 index 0000000..9f64e8d --- /dev/null +++ b/assets/components_i18n-t.md.Dn3NUPHA.js @@ -0,0 +1,31 @@ +import{_ as i,c as a,a2 as t,o as n}from"./chunks/framework.CBrKbnPu.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="itemCount" />
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, locale: string) => string
<i18n-t
+ keypath="items"
+ :plural="itemCount"
+ :customPluralRule="(key, count, locale, getTranslation) => {
+ const translation = getTranslation(key, {})
+ 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="itemCount" />
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, locale: string) => string
<i18n-t
+ keypath="items"
+ :plural="itemCount"
+ :customPluralRule="(key, count, locale, getTranslation) => {
+ const translation = getTranslation(key, {})
+ 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>
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>
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.
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
).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.
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
).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 npm.
npm install
+npm run prepack && cd playground && npm run prepare && cd ..
To start the development server and work on the module, run the following command:
npm 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:
npm 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:
npm run lint
If there are any issues, you can attempt to automatically fix them using:
npm run lint:fix
To run the test suite, use the following command:
npm run test
This will run all the Playwright tests to ensure everything is functioning as expected.
For TypeScript type checking, run:
npm run typecheck
This checks the type definitions to ensure there are no type errors.
To build and preview the documentation locally, use the following commands:
npm run docs:build
+npm 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:
npm run dev:build
You can access the playground app at http://localhost:3000
.
npm run dev
: Start the development server using the playground.npm run prepack
: Build the module and prepare it for publishing.npm run lint
: Run the linter to check for code quality issues.npm run lint:fix
: Automatically fix linter issues.npm run test
: Run the test suite.npm run typecheck
: Check TypeScript types.npm run docs:dev
: Start the documentation site in development mode.npm run docs:build
: Build the documentation site.npm run docs:serve
: Serve the built documentation site locally.npm 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:
npm run lint
Fix any linting errors before proceeding.
Make sure your changes work and do not break any existing functionality:
npm 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
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 npm.
npm install
+npm run prepack && cd playground && npm run prepare && cd ..
To start the development server and work on the module, run the following command:
npm 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:
npm 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:
npm run lint
If there are any issues, you can attempt to automatically fix them using:
npm run lint:fix
To run the test suite, use the following command:
npm run test
This will run all the Playwright tests to ensure everything is functioning as expected.
For TypeScript type checking, run:
npm run typecheck
This checks the type definitions to ensure there are no type errors.
To build and preview the documentation locally, use the following commands:
npm run docs:build
+npm 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:
npm run dev:build
You can access the playground app at http://localhost:3000
.
npm run dev
: Start the development server using the playground.npm run prepack
: Build the module and prepare it for publishing.npm run lint
: Run the linter to check for code quality issues.npm run lint:fix
: Automatically fix linter issues.npm run test
: Run the test suite.npm run typecheck
: Check TypeScript types.npm run docs:dev
: Start the documentation site in development mode.npm run docs:build
: Build the documentation site.npm run docs:serve
: Serve the built documentation site locally.npm 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:
npm run lint
Fix any linting errors before proceeding.
Make sure your changes work and do not break any existing functionality:
npm 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
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.DEb4srNU.lean.js b/assets/guide_crowdin.md.DEb4srNU.lean.js new file mode 100644 index 0000000..619b2c5 --- /dev/null +++ b/assets/guide_crowdin.md.DEb4srNU.lean.js @@ -0,0 +1,16 @@ +import{_ as a,c as s,a2 as n,o as e}from"./chunks/framework.CBrKbnPu.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.DeZ1f3q2.js b/assets/guide_custom-locale-routes.md.DeZ1f3q2.js new file mode 100644 index 0000000..3bdf3ac --- /dev/null +++ b/assets/guide_custom-locale-routes.md.DeZ1f3q2.js @@ -0,0 +1,35 @@ +import{_ as i,c as a,a2 as e,o as t}from"./chunks/framework.CBrKbnPu.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.One common issue when using Nuxt I18n Micro
is that some routes might not open as expected. This can happen when the router doesn’t automatically assign a name to a route, particularly in subfolders.
Solution: To fix this, manually define the page’s route name by adding the following to the corresponding Vue file:
definePageMeta({ name: 'pageName' })
This ensures that the route is properly registered, and the application can navigate to it without issues.
assets/_locales/
folder added to the server folder? When deploying to platforms like Netlify, the build process might behave differently compared to local development. This can lead to issues where certain files or folders are not found during server-side rendering (SSR).
To ensure that localization files are available during SSR, the assets/_locales/
folder is added to the server folder. This is a workaround to make sure that the localization files are accessible in the production environment, especially when the build process and runtime environment differ.
Explanation:
$fetch
in SSR, leading to middleware not finding the localization files.Nuxt I18n Micro
inspired by vue-i18n
? What about features like modifiers? While Nuxt I18n Micro
serves as a performance alternative to nuxt-i18n
, it is not directly inspired by vue-i18n
. The library was built from scratch to address issues in nuxt-i18n
, and while some method names and parameters are similar, the underlying logic is entirely different.
Modifiers: The maintainer experimented with adding modifiers but found that components like <i18n-t>
and <i18n-link>
effectively cover the same 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>
Since this approach is flexible and powerful, releasing modifiers was deemed unnecessary for now. However, modifiers may be added in the future if demand arises.
NuxtLink
or i18nLink
directly in translation strings? Yes, Nuxt I18n Micro
allows you to use NuxtLink
or i18nLink
in translations through the <i18n-t>
component, eliminating the need to split translation strings, which can be especially helpful when dealing with languages that have different grammatical rules or RTL languages.
Example:
{
+ "example": "Share your {link} with friends",
+ "link_text": "translation link"
+}
<template>
+ <i18n-t keypath="example">
+ <template #link>
+ <nuxt-link :to="{ name: 'referral' }">
+ <i18n-t keypath="link_text" />
+ </nuxt-link>
+ </template>
+ </i18n-t>
+</template>
This method supports dynamic link creation inside translations while maintaining proper localization structure.
`,25)]))}const g=i(n,[["render",l]]);export{E as __pageData,g as default}; diff --git a/assets/guide_faq.md.Vyfgzyoq.lean.js b/assets/guide_faq.md.Vyfgzyoq.lean.js new file mode 100644 index 0000000..fe9c5e4 --- /dev/null +++ b/assets/guide_faq.md.Vyfgzyoq.lean.js @@ -0,0 +1,20 @@ +import{_ as i,c as a,a2 as e,o as t}from"./chunks/framework.CBrKbnPu.js";const E=JSON.parse('{"title":"FAQ: Common Issues & Solutions","description":"","frontmatter":{"outline":"deep"},"headers":[],"relativePath":"guide/faq.md","filePath":"guide/faq.md","lastUpdated":1729616442000}'),n={name:"guide/faq.md"};function l(h,s,p,r,k,o){return t(),a("div",null,s[0]||(s[0]=[e(`One common issue when using Nuxt I18n Micro
is that some routes might not open as expected. This can happen when the router doesn’t automatically assign a name to a route, particularly in subfolders.
Solution: To fix this, manually define the page’s route name by adding the following to the corresponding Vue file:
definePageMeta({ name: 'pageName' })
This ensures that the route is properly registered, and the application can navigate to it without issues.
assets/_locales/
folder added to the server folder? When deploying to platforms like Netlify, the build process might behave differently compared to local development. This can lead to issues where certain files or folders are not found during server-side rendering (SSR).
To ensure that localization files are available during SSR, the assets/_locales/
folder is added to the server folder. This is a workaround to make sure that the localization files are accessible in the production environment, especially when the build process and runtime environment differ.
Explanation:
$fetch
in SSR, leading to middleware not finding the localization files.Nuxt I18n Micro
inspired by vue-i18n
? What about features like modifiers? While Nuxt I18n Micro
serves as a performance alternative to nuxt-i18n
, it is not directly inspired by vue-i18n
. The library was built from scratch to address issues in nuxt-i18n
, and while some method names and parameters are similar, the underlying logic is entirely different.
Modifiers: The maintainer experimented with adding modifiers but found that components like <i18n-t>
and <i18n-link>
effectively cover the same 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>
Since this approach is flexible and powerful, releasing modifiers was deemed unnecessary for now. However, modifiers may be added in the future if demand arises.
NuxtLink
or i18nLink
directly in translation strings? Yes, Nuxt I18n Micro
allows you to use NuxtLink
or i18nLink
in translations through the <i18n-t>
component, eliminating the need to split translation strings, which can be especially helpful when dealing with languages that have different grammatical rules or RTL languages.
Example:
{
+ "example": "Share your {link} with friends",
+ "link_text": "translation link"
+}
<template>
+ <i18n-t keypath="example">
+ <template #link>
+ <nuxt-link :to="{ name: 'referral' }">
+ <i18n-t keypath="link_text" />
+ </nuxt-link>
+ </template>
+ </i18n-t>
+</template>
This method supports dynamic link creation inside translations while maintaining proper localization structure.
`,25)]))}const g=i(n,[["render",l]]);export{E as __pageData,g as default}; diff --git a/assets/guide_folder-structure.md.Cky6Juvc.js b/assets/guide_folder-structure.md.Cky6Juvc.js new file mode 100644 index 0000000..96c6dbd --- /dev/null +++ b/assets/guide_folder-structure.md.Cky6Juvc.js @@ -0,0 +1,44 @@ +import{_ as s,c as e,a2 as n,o as i}from"./chunks/framework.CBrKbnPu.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.Cky6Juvc.lean.js b/assets/guide_folder-structure.md.Cky6Juvc.lean.js new file mode 100644 index 0000000..96c6dbd --- /dev/null +++ b/assets/guide_folder-structure.md.Cky6Juvc.lean.js @@ -0,0 +1,44 @@ +import{_ as s,c as e,a2 as n,o as i}from"./chunks/framework.CBrKbnPu.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.-u7BlIMn.js b/assets/guide_getting-started.md.-u7BlIMn.js new file mode 100644 index 0000000..5096aea --- /dev/null +++ b/assets/guide_getting-started.md.-u7BlIMn.js @@ -0,0 +1,69 @@ +import{_ as i,c as a,a2 as e,o as t}from"./chunks/framework.CBrKbnPu.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":1729515293000}'),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:
locales
Defines the locales available in your application.
Type: Locale[]
Each locale object includes:
code
(string, required): A unique identifier for the locale, e.g., 'en'
for English.iso
(string, optional): The ISO code, e.g., 'en-US'
, used for the lang
attribute in HTML.dir
(string, optional): Text direction, either 'rtl'
for right-to-left or 'ltr'
for left-to-right languages.disabled
(boolean, optional): Indicates if the locale should be disabled.Example:
locales: [
+ { code: 'en', iso: 'en-US', dir: 'ltr' },
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr' },
+ { code: 'ar', iso: 'ar-SA', dir: 'rtl', disabled: false }
+]
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 the locale auto-detection and switching should occur.
Type: string
Default: "*"
Example:
autoDetectPath: '/' // Locale detection will only happen on the home route
plural
Custom function for handling pluralization in translations based on count and locale.
Type: (key: string, translation: unknown, count: number, locale: string) => string
Example:
export type Getter = (key: string, params?: Record<string, string | number | boolean>, defaultValue?: string) => unknown
+
+{
+ plural: (key: string, count: number, _locale: string, t: Getter) => {
+ const translation = t(key)
+ if (!translation) {
+ return key
+ }
+ const forms = translation.toString().split('|')
+ if (count === 0 && forms.length > 2) {
+ return forms[0].trim() // Case for "no apples"
+ }
+ if (count === 1 && forms.length > 1) {
+ return forms[1].trim() // Case for "one apple"
+ }
+ return (forms.length > 2 ? forms[2].trim() : forms[forms.length - 1].trim()).replace('{count}', count.toString())
+ }
+}
includeDefaultLocaleRoute
Automatically redirects routes without a locale prefix to the default locale.
Type: boolean
Default: false
Example:
includeDefaultLocaleRoute: true // Ensure consistency across routes by redirecting to the default locale
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
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
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',
+ fallbackLocale: 'en', // Use English as a fallback locale
+}
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: false, // Unlocalized page should not be localized
+}
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.
`,132)]))}const g=i(n,[["render",l]]);export{c as __pageData,g as default}; diff --git a/assets/guide_getting-started.md.-u7BlIMn.lean.js b/assets/guide_getting-started.md.-u7BlIMn.lean.js new file mode 100644 index 0000000..5096aea --- /dev/null +++ b/assets/guide_getting-started.md.-u7BlIMn.lean.js @@ -0,0 +1,69 @@ +import{_ as i,c as a,a2 as e,o as t}from"./chunks/framework.CBrKbnPu.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":1729515293000}'),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:
locales
Defines the locales available in your application.
Type: Locale[]
Each locale object includes:
code
(string, required): A unique identifier for the locale, e.g., 'en'
for English.iso
(string, optional): The ISO code, e.g., 'en-US'
, used for the lang
attribute in HTML.dir
(string, optional): Text direction, either 'rtl'
for right-to-left or 'ltr'
for left-to-right languages.disabled
(boolean, optional): Indicates if the locale should be disabled.Example:
locales: [
+ { code: 'en', iso: 'en-US', dir: 'ltr' },
+ { code: 'fr', iso: 'fr-FR', dir: 'ltr' },
+ { code: 'ar', iso: 'ar-SA', dir: 'rtl', disabled: false }
+]
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 the locale auto-detection and switching should occur.
Type: string
Default: "*"
Example:
autoDetectPath: '/' // Locale detection will only happen on the home route
plural
Custom function for handling pluralization in translations based on count and locale.
Type: (key: string, translation: unknown, count: number, locale: string) => string
Example:
export type Getter = (key: string, params?: Record<string, string | number | boolean>, defaultValue?: string) => unknown
+
+{
+ plural: (key: string, count: number, _locale: string, t: Getter) => {
+ const translation = t(key)
+ if (!translation) {
+ return key
+ }
+ const forms = translation.toString().split('|')
+ if (count === 0 && forms.length > 2) {
+ return forms[0].trim() // Case for "no apples"
+ }
+ if (count === 1 && forms.length > 1) {
+ return forms[1].trim() // Case for "one apple"
+ }
+ return (forms.length > 2 ? forms[2].trim() : forms[forms.length - 1].trim()).replace('{count}', count.toString())
+ }
+}
includeDefaultLocaleRoute
Automatically redirects routes without a locale prefix to the default locale.
Type: boolean
Default: false
Example:
includeDefaultLocaleRoute: true // Ensure consistency across routes by redirecting to the default locale
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
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
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',
+ fallbackLocale: 'en', // Use English as a fallback locale
+}
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: false, // Unlocalized page should not be localized
+}
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.
`,132)]))}const g=i(n,[["render",l]]);export{c as __pageData,g as default}; diff --git a/assets/guide_layers.md.Dy4zl8SE.js b/assets/guide_layers.md.Dy4zl8SE.js new file mode 100644 index 0000000..5c5d92c --- /dev/null +++ b/assets/guide_layers.md.Dy4zl8SE.js @@ -0,0 +1,72 @@ +import{_ as i,c as a,a2 as n,o as t}from"./chunks/framework.CBrKbnPu.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.
The performance tests conducted for Nuxt I18n Micro
and nuxt-i18n
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.
The performance tests conducted for Nuxt I18n Micro
and nuxt-i18n
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.SXcHzDO5.lean.js b/assets/guide_performance.md.SXcHzDO5.lean.js new file mode 100644 index 0000000..4d95d03 --- /dev/null +++ b/assets/guide_performance.md.SXcHzDO5.lean.js @@ -0,0 +1 @@ +import{_ as r,c as o,a2 as n,o as a}from"./chunks/framework.CBrKbnPu.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.BpSpRrpu.js b/assets/guide_seo.md.BpSpRrpu.js new file mode 100644 index 0000000..de67253 --- /dev/null +++ b/assets/guide_seo.md.BpSpRrpu.js @@ -0,0 +1,13 @@ +import{_ as e,c as s,a2 as a,o as n}from"./chunks/framework.CBrKbnPu.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
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
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>
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