i18n Plugin¶
The i18n Plugin provides internationalization support for VC-Shell applications, enabling multi-language interfaces and localized content. It's built on top of vue-i18n and is deeply integrated with the framework.
Features¶
- Multi-language Support: Support for multiple languages with runtime language switching
- Message Format: Support for complex message formatting, including pluralization and datetime formatting
- Fallback Handling: Graceful fallback to default language when translations are missing
- Vee-Validate Integration: Synchronization with the validation system for localized validation messages
- Dynamic Loading: Ability to load language files on demand
Setup and Configuration¶
The i18n plugin is initialized when you install the VcShellFramework
. The recommended way to configure the default and fallback languages is through environment variables.
Environment Variables¶
In your project's .env
file, you can specify the following keys:
These variables are then used during the framework's initialization in your main.ts
file to set up vue-i18n
. This allows you to easily change locales for different environments (development, staging, production) without modifying your code. A complete example of the main.ts
initialization is available in the "Adding Translations" section below.
Accessing i18n¶
In Templates¶
You can use the Vue I18n template syntax to display localized messages:
<template>
<div>
<h1>{{ $t('welcome') }}</h1>
<p>{{ $t('messages.hello', { name: user.name }) }}</p>
<div>{{ $tc('items', count) }}</div>
</div>
</template>
In JavaScript/TypeScript¶
import { useI18n } from 'vue-i18n';
export default {
setup() {
const { t, locale } = useI18n();
// Get translated message
const welcome = t('welcome');
// Change language
function changeLanguage(lang) {
locale.value = lang;
}
return { welcome, changeLanguage };
}
};
Adding Translations¶
Translations are crucial for multi-language support. VC-Shell's i18n plugin, built on vue-i18n
, facilitates this. Here's how translations are typically added:
1. For the Main Application¶
Application-specific translations (those not part of a distinct reusable module) are usually defined in JSON files within the application's locales
directory (e.g., src/locales/en.json
). These are then registered in the application's entry point (e.g., main.ts
).
VC-Shell provides a convenient way to merge these locales, typically made available as app.config.globalProperties.$mergeLocaleMessage
.
Recommended approach (typically in main.ts
):
// main.ts
import { createApp } from 'vue';
import VcShellFramework, { useLanguages } from '@vc-shell/framework';
import { router } from './router';
import App from './App.vue'; // Assuming a root App component
// Assuming an index.ts in locales/ exports all: export * as en from './locales/en.json';
import * as appLocales from './locales';
async function startApp() {
// Potentially load user data or other async setup here first
// await useUser().loadUser();
const app = createApp(App);
app.use(VcShellFramework, {
router,
i18n: {
locale: import.meta.env.APP_I18N_LOCALE,
fallbackLocale: import.meta.env.APP_I18N_FALLBACK_LOCALE,
}
});
// Merge application-specific locales
Object.entries(appLocales).forEach(([localeKey, localeModule]) => {
// Extract messages, handling ES module default exports if locales are imported with `import *`
const messages = localeModule.default || localeModule;
app.config.globalProperties.$mergeLocaleMessage(localeKey, messages);
});
// Initialize language using useLanguages after all locales are merged
const { currentLocale, setLocale } = useLanguages();
setLocale(currentLocale.value); // Applies stored preference or default
app.mount('#app');
}
startApp();
vue-i18n
instance. For more detailed steps and context, refer to the How-To: Adding New Languages guide.
2. For VC-Shell Modules¶
Modules within VC-Shell (e.g., feature modules in src/modules/
or shared modules) should bundle their own translations in their respective locales
directories.
When these modules are registered with the application (e.g., using createAppModule
from @vc-shell/framework/core/plugins/modularity
), the VC-Shell modularity system automatically merges the module's locale messages into the global vue-i18n
instance.
This process typically uses i18n.global.mergeLocaleMessage()
internally, where i18n
is the global vue-i18n
instance provided by the framework. Module developers usually just need to provide the locale files as part of their module's definition, and the framework handles the registration.
Example (Conceptual module definition from my-module/index.ts
):
import enMessages from './locales/en.json';
import frMessages from './locales/fr.json';
import { createAppModule } from '@vc-shell/framework/core/plugins/modularity';
// ... other module components, pages etc.
export default createAppModule(
{ /* pages */ },
{ // Locales object
en: enMessages,
fr: frMessages
},
{ /* notificationTemplates */ },
{ /* moduleComponents */ }
);
Using the useLanguages Composable¶
VC-Shell provides a useLanguages
composable for managing languages:
import { useLanguages } from '@vc-shell/framework';
export default {
setup() {
const {
setLocale, // Function to change the current locale
currentLocale, // ComputedRef with the current locale
getLocaleByTag, // Function to get locale name by tag
resolveCamelCaseLocale, // Function to normalize locale format
getFlag // Function to get flag icon for a language
} = useLanguages();
// Change language
function changeToFrench() {
setLocale('fr');
}
// Get native language name
const frenchName = getLocaleByTag('fr');
return {
currentLocale,
changeToFrench,
frenchName
};
}
};
Date and Number Formatting¶
Vue I18n includes built-in support for formatting dates, times, and numbers:
<template>
<div>
<p>{{ $d(date, 'long') }}</p>
<p>{{ $n(amount, 'currency') }}</p>
</div>
</template>
<script>
export default {
setup() {
return {
date: new Date(),
amount: 1234.56
};
}
};
</script>
Integration with Vee-Validate¶
The i18n Plugin is integrated with Vee-Validate for localized validation messages:
import { setLocale as setVeeI18nLocale } from '@vee-validate/i18n';
// In useLanguages composable
function setLocale(locale: string) {
i18n.global.locale.value = locale;
setVeeI18nLocale(locale);
}
Best Practices¶
-
Organized Structure: Organize translations in a logical, hierarchical structure with namespaced keys.
-
Complete Translations: Ensure each language file contains all the keys, even if some translations are temporary placeholders.
-
Language Names: Always include a
language_name
key in each language file with the native name of that language. -
Pluralization: Use Vue I18n's pluralization features for messages that vary by count.
-
Parameterized Messages: Use parameters for dynamic parts of messages rather than concatenating strings.
-
Consistent Naming: Use consistent naming conventions for translation keys.
-
Default Language: Always have a complete and up-to-date default language file as a fallback.
Related Resources¶
- Vue I18n Documentation: The official documentation for the underlying
vue-i18n
library. - How-To: Adding New Languages: A practical guide for adding and managing languages in applications and modules.
- useLanguages Composable: Documentation for the composable used to manage language settings.