Research
Security News
Malicious npm Package Targets Solana Developers and Hijacks Funds
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
nuxt-i18n-micro
Advanced tools
Nuxt I18n Micro is a lightweight, high-performance internationalization module for Nuxt, designed to handle multi-language support with minimal overhead, fast build times, and efficient runtime performance.
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:
Nuxt I18n Micro:
Nuxt I18n:
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
locales/{locale}.json
(e.g., locales/en.json
). Used for common texts shared across multiple pages, such as menus.locales/pages/{routeName}/{locale}.json
(e.g., locales/pages/index/en.json
). These are used for translations specific to individual pages.$getLocale()
Returns the current locale code.
const locale = $getLocale()
$getLocales()
Returns an array of all available locales configured in the module.
const locales = $getLocales()
$t(key: string, params?: Record<string, any>, defaultValue?: string)
Fetches a translation for the given key. Optionally interpolates parameters into the translation.
const welcomeMessage = $t('welcome', { username: 'Alice', unreadCount: 5 })
$tc(key: string, count: number, defaultValue?: string)
Fetches a pluralized translation for the given key based on the count.
const appleCountMessage = $tc('apples', 10)
$switchLocale(locale: string)
Switches to the given locale and redirects the user to the appropriate localized route.
$switchLocale('fr')
$localeRoute(to: RouteLocationRaw, locale?: string): RouteLocationRaw
Generates a localized route object based on the target route.
const localizedRoute = $localeRoute({ name: 'index' })
$mergeTranslations(newTranslations: Translations)
Merges new translations into the existing translation cache for the current route and locale.
$mergeTranslations({
welcome: 'Bienvenue, {username}!'
})
$defineI18nRoute(routeDefinition: { locales?: string[] | Record<string, Record<string, TranslationObject>> })
Defines route behavior based on the current locale. This method can be used to control access to specific routes based on available locales or to provide translations for specific locales.
locales
: This property determines which locales are available for the route. It can be either:
['en', 'fr', 'de']
).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.import { useNuxtApp } from '#imports'
const { $getLocale, $switchLocale, $getLocales, $localeRoute, $t } = useNuxtApp()
import { useI18n } from '#imports'
const { $getLocale, $switchLocale, $getLocales, $localeRoute, $t } = useI18n()
// or
const i18n = useI18n()
<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>
Вот обновленный раздел README.md
с описанием работы параметра routesLocaleLinks
и улучшенным оформлением параметров модуля.
The module accepts the following options in the Nuxt configuration:
Locale[]
interface Locale {
code: string
disabled?: boolean
iso?: string
dir?: 'rtl' | 'ltr'
}
An array of locale objects. Each locale should have the following properties:
code
: (string, required) A unique identifier for the locale, such as 'en'
for English or 'fr'
for French.iso
: (string, optional) The ISO code for the locale, which is typically used for setting the lang
attribute in HTML or for other internationalization purposes (e.g., 'en-US'
, 'fr-FR'
).dir
: (string, optional) The text direction for the locale. It can be either 'rtl'
for right-to-left languages (like Arabic or Hebrew) or 'ltr'
for left-to-right languages (like English or French).disabled
: (boolean, optional) A flag indicating whether this locale should be disabled or excluded from certain layers or operations.Example:
locales: [
{ code: 'en', iso: 'en' },
{ code: 'fr' },
{ code: 'ar', iso: 'ar-SA', dir: 'rtl' }
]
boolean
Indicates whether to automatically generate SEO-related meta tags (like alternate
links).
string
The default locale code. For example, 'en'
.
string
The directory where translation files are stored. Default value is 'locales'
.
boolean
If true
, the module automatically detects the user's preferred language and redirects accordingly.
function
A custom function for handling pluralization logic.
boolean
If true
, all routes without a locale prefix will redirect to the default locale route.
Record<string, string>
This parameter allows you to create links between different pages' locale files. It is particularly useful in cases where you have similar pages (e.g., a main page and a page with a slug) and want them to share the same translation file.
For example, if you have a page with a slug (dir1-slug
) and a main page (index
), you can set up routesLocaleLinks
so that dir1-slug
will use the locale file of index
, avoiding the need to maintain duplicate translation files.
Note: dir1-slug
and index
refer to the names of the routes, which you can inspect in the devtools.
Example:
export default defineNuxtConfig({
i18n: {
routesLocaleLinks: {
'dir1-slug': 'index',
},
},
})
In this example, the page with the route name dir1-slug
will load its translations from the locale file associated with the index
route.
boolean
(In development) This option is designed to optimize performance when working with large JSON translation files. When enabled, it caches translations specific to the current page, reducing search times and minimizing client-side load.
The Nuxt I18n Micro
module provides an efficient way to manage internationalization (i18n) in your Nuxt application, with a focus on performance and simplicity. One of the key features of this module is how it handles the loading of locale-specific translations. Below is an explanation of how this process works.
In Nuxt I18n Micro
, translations are loaded dynamically based on the user's selected locale. The module uses a specific route pattern (/_locales/:page/:locale/data.json
) to fetch the translation files for each page and locale. This approach is designed to minimize the initial load time and only load the necessary translations for the current page and locale.
The translations are organized into JSON files located in the locales
directory. These files are split into:
locales/{locale}.json
(e.g., locales/en.json
). These files contain translations shared across the entire application, such as menu items or common UI elements.locales/pages/{routeName}/{locale}.json
(e.g., locales/pages/index/en.json
). These files contain translations specific to individual pages.To accommodate the dynamic nature of translation loading, Nuxt I18n Micro
extends the default routing configuration by adding locale-specific routes. This means that for each page, a localized version of the route is generated. For example, if your application has an index
page and supports English (en
) and French (fr
), the following routes would be generated:
/en/index
/fr/index
This structure allows the module to load the appropriate translations based on the user's selected locale.
Given the way Vite and Nuxt handle modules, the Nuxt I18n Micro
module uses a special route (/_locales/:page/:locale/data.json
) to fetch translations. This is necessary because, during the build process, Vite may not bundle all translation files directly into the application. Instead, the module dynamically loads these files from the server as needed.
When a user navigates to a page, the module will:
_locales
route to fetch the required translation file.To further optimize performance, Nuxt I18n Micro
supports caching and pre-rendering of translation files:
Certainly! Here's an updated section for your README that includes the description of the <i18n-t>
component, along with explanations for each prop and examples of usage.
<i18n-t>
ComponentThe <i18n-t>
component in Nuxt I18n Micro
is a flexible and powerful tool designed to handle translations within your Nuxt application. It supports various features such as interpolation, pluralization, and dynamic HTML rendering.
keypath
(string
, required): The translation key used to look up the corresponding translation string from the locale files.
plural
(number | null
, optional): The count used for pluralization. If provided, the component will use the $tc
method for translating based on the pluralization rules defined for the locale.
tag
(string
, optional, default: 'span'
): The HTML tag used to wrap the translated content. You can specify any valid HTML tag, such as div
, p
, h1
, etc.
scope
(string
, optional, default: 'global'
): Specifies the scope of the translation. This prop is useful if you have different translation scopes in your application, although the default is set to 'global'
.
params
(Record<string, string | number | boolean>
, optional, default: () => ({})
): An object containing key-value pairs to be interpolated into the translation string. This is useful for dynamic translations where certain values need to be inserted into the text.
defaultValue
(string
, optional, default: ''
): A fallback translation that will be displayed if the keypath
does not match any key in the translation files.
html
(boolean
, optional, default: false
): A flag indicating whether the translation contains HTML. When set to true
, the translated string will be rendered as raw HTML.
locale
(string
, optional): The locale to use for this translation. If not provided, the component will use the current locale set by the application.
wrap
(boolean
, optional, default: true
): Determines if the translated content should be wrapped in the specified tag
. If set to false
, the component will not wrap the translation in an HTML element.
customPluralRule
((value: string, count: number, locale: string) => string
, optional): A custom function for handling pluralization. This allows you to override the default pluralization behavior with your custom logic.
hideIfEmpty
(boolean
, optional, default: false
): If true
, the component will not render anything if the translation string is empty. This is useful for conditional rendering based on the presence of a translation.
<i18n-t keypath="welcomeMessage"></i18n-t>
This will render the translation associated with the key welcomeMessage
using the current locale.
<i18n-t keypath="apples" :plural="10" tag="div"></i18n-t>
This will handle the pluralization for the translation key apples
and render it inside a div
element.
<i18n-t keypath="greeting" :params="{ name: 'John' }"></i18n-t>
Assuming the translation string is "Hello, {name}!"
, this will render "Hello, John!"
.
<i18n-t keypath="richText" :html="true"></i18n-t>
If richText
contains HTML content like "<strong>Welcome</strong> to our site!"
, setting html
to true
will render the HTML directly.
<i18n-t keypath="welcomeMessage" locale="fr"></i18n-t>
This will render the translation in French, overriding the application's current locale.
<i18n-t keypath="optionalMessage" :hideIfEmpty="true"></i18n-t>
This will render nothing if the translation for optionalMessage
is empty.
<i18n-t
keypath="items"
:plural="itemCount"
:customPluralRule="(value, count, locale) => {
return count === 1 ? 'One item' : value.replace('{count}', `${count}`)
}"></i18n-t>
This uses a custom function to handle the pluralization, bypassing the default logic.
<i18n-t
keypath="notifications"
:plural="unreadCount"
tag="p"
:params="{ username: 'Alice' }"
defaultValue="You have no notifications"
:html="false"
locale="en"
:wrap="true"
:hideIfEmpty="false">
</i18n-t>
Here's how you can use the slot and access the translation
within it:
<i18n-t keypath="welcomeMessage">
<template #default="{ translation }">
<strong>{{ translation }}</strong>
</template>
</i18n-t>
translation
:
translation
as a slot prop, which can be accessed in the parent component’s slot content.<strong>
tag, allowing you to apply custom styling or further modify how the translation is displayed.The <i18n-t>
component provides a powerful and flexible way to handle translations in your Nuxt application, accommodating a wide range of use cases from simple text translations to complex pluralization and HTML rendering scenarios.
In Nuxt I18n Micro
, you can use the concept of layers to manage localization settings in your application. This approach allows you to configure internationalization flexibly depending on the context, and it also enables you to create and extend locale configurations across different parts of your application.
The primary configuration layer (i18n
) sets the default localization settings used throughout the application. In this layer, you define the main locales, the order in which they are used, SEO settings, behavior for detecting the user's language, and other relevant parameters.
Example of a basic configuration in the primary layer:
export default defineNuxtConfig({
i18n: {
locales: [
{ code: 'en', iso: 'en_EN' },
{ code: 'de', iso: 'de_DE' },
],
meta: true, // Enable automatic SEO meta tags generation
defaultLocale: 'en', // Default language
translationDir: 'locales', // Directory for translation files
autoDetectLanguage: true, // Automatically detect the user's language
},
})
Child layers allow you to extend or modify the configuration set in the primary layer. This is particularly useful if you need to adapt localization settings for specific contexts or sections of your application while retaining the overall base configuration.
Example of using a child layer:
export default defineNuxtConfig({
extends: '../basic', // Inherit the base configuration layer
i18n: {
locales: [
{ code: 'ru', iso: 'ru_RU' }, // Add a new locale for Russian
{ code: 'de', disabled: true }, // Disable the locale for German
],
},
})
In this example:
extends: '../basic'
.ru
for Russian.de
locale by setting disabled: true
.Nuxt I18n Micro
offers a highly efficient, minimalist approach to internationalization in Nuxt applications. By focusing on performance and simplicity, it provides a powerful alternative to heavier, more complex i18n solutions. Whether you're building a small website or a large-scale application, Nuxt I18n Micro
helps you manage multilingual content with ease.
For more details and updates, visit the Nuxt I18n Micro GitHub repository.
FAQs
Nuxt I18n Micro is a lightweight, high-performance internationalization module for Nuxt, designed to handle multi-language support with minimal overhead, fast build times, and efficient runtime performance.
The npm package nuxt-i18n-micro receives a total of 851 weekly downloads. As such, nuxt-i18n-micro popularity was classified as not popular.
We found that nuxt-i18n-micro demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
Security News
Research
Socket researchers have discovered malicious npm packages targeting crypto developers, stealing credentials and wallet data using spyware delivered through typosquats of popular cryptographic libraries.
Security News
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.