### Git Workflow Example Source: https://github.com/intlify/vue-i18n-extensions/blob/next/CONTRIBUTING.md Example steps for forking, branching, committing, and submitting a pull request. ```bash git branch my-new-topic origin/master git commit -am 'Add some topic' git push origin my-new-topic ``` -------------------------------- ### Install Dependencies Source: https://github.com/intlify/vue-i18n-extensions/blob/next/CONTRIBUTING.md Install project dependencies using pnpm. ```bash pnpm install ``` -------------------------------- ### Install @intlify/vue-i18n-extensions Source: https://github.com/intlify/vue-i18n-extensions/blob/next/README.md Install the library using npm, pnpm, or yarn. Ensure you are installing the '@next' version for Vue 3 development. ```sh # npm npm i --save-dev @intlify/vue-i18n-extensions@next # pnpm pnpm add -D @intlify/vue-i18n-extensions@next # yarn yarn add -D @intlify/vue-i18n-extensions@next ``` -------------------------------- ### Run Development Server Source: https://github.com/intlify/vue-i18n-extensions/blob/next/CONTRIBUTING.md Start the development server with hot reloading for unit tests. ```bash pnpm dev ``` -------------------------------- ### Build Tool Error Output Examples Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/errors.md Examples of error messages that may appear in the terminal during build processes with Webpack/Vue Loader and Vite. ```bash # Output during build [vue-i18n-extensions] Unexpected directive expression:
[vue-i18n-extensions] v-t will override element children:
...
``` ```bash # Terminal output [vue-i18n-extensions] FAILED_VALUE_EVALUATION: Failed value evaluation:
``` -------------------------------- ### Example Translation Signature Resolution Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/expression-parsing.md Shows an example of how translation signatures are resolved, including prefixing based on binding metadata and context. ```javascript translationSignatures: ['customT', 't'] prefixIdentifiers: true bindingMetadata: { t: 'setup' } Output: "($setup.customT || $setup.t || $t)" ``` -------------------------------- ### SSR Handler Setup with Vue i18n Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/integration-guide.md Implement server-side rendering by creating a fresh `vue-i18n` instance for each request, installing it on the Vue app, and then rendering the app to a string. This ensures isolated contexts for each request. ```typescript import { createSSRApp } from 'vue' import { renderToString } from '@vue/server-renderer' import { createI18n } from 'vue-i18n' import App from './App.vue' export async function render(url, manifest) { // Create fresh i18n instance for each request const i18n = createI18n({ legacy: false, locale: 'en', messages: { /* ... */ } }) // Create app const app = createSSRApp(App) // Install i18n app.use(i18n) // Render to string const html = await renderToString(app) return { html } ``` -------------------------------- ### v-t Directive Object with Options Example Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/README.md Provides an example of using the `v-t` directive with an object containing translation path and arguments. ```html

``` -------------------------------- ### TypeScript Support Example Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/README.md Demonstrates how to use TypeScript with `transformVTDirective` for type-safe internationalization. ```typescript type Messages = { greeting: string } const transformVT = transformVTDirective({ /* ... */ }) ``` -------------------------------- ### Create a ContentBuilder Instance Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/api-reference/createContentBuilder.md Initializes a ContentBuilder with default options. Use this to start building formatted strings. ```typescript export function createContentBuilder( options?: ContentBuilderOptions ): ContentBuilder ``` -------------------------------- ### Multi-Mode Setup for Composition and Legacy APIs Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/integration-guide.md Integrate both Composition API and legacy API modes by configuring separate `transformVTDirective` instances for each. This setup is useful for applications supporting both styles. ```typescript // vite.config.ts import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import { transformVTDirective } from '@intlify/vue-i18n-extensions' import { createI18nInstance } from './src/i18n.config' const i18n = createI18nInstance() // Most components use composition API const compositionTransform = transformVTDirective({ i18n, mode: 'composition' }) // Fallback for legacy components const legacyTransform = transformVTDirective({ i18n, mode: 'legacy' }) export default defineConfig({ plugins: [ vue({ template: { compilerOptions: { directiveTransforms: { t: compositionTransform } } } }) ] }) // Note: To use both, you'd need separate build configurations // or use a custom resolver that detects component style ``` -------------------------------- ### Object Expression with Args Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/expression-parsing.md An example of an object expression with arguments, demonstrating how nested properties are analyzed for pre-translation. ```javascript { path: 'msg.greeting', args: { name: 'John' } } ``` -------------------------------- ### Deep Nesting Example Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/directive-syntax-reference.md Demonstrates how to use the v-t directive with deeply nested arguments for dynamic content. ```vue
``` -------------------------------- ### v-t Directive Variable Example Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/README.md Shows how to use the `v-t` directive with a variable that holds the translation key. ```html

``` -------------------------------- ### Example: Handling Multiple i18n Instances Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/configuration.md Configure 'translationSignatures' with an array of potential function names to support applications using multiple distinct i18n instances. ```typescript const transformVT = transformVTDirective({ translationSignatures: ['i18nA', 'i18nB', 'i18n', 't'] // Supports components using different i18n instances }) ``` -------------------------------- ### v-t Directive String Literal Example Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/README.md Demonstrates the usage of the `v-t` directive with a simple string literal for translation. ```html

``` -------------------------------- ### Example: Per-Module Translation Signatures Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/configuration.md Implement a resolver function to map different modules or directories to specific translation functions, allowing for granular i18n management. ```typescript const transformVT = transformVTDirective({ translationSignatures: (context, baseResolver) => { const { filename } = context // Map modules to custom translation functions const signatureMap = { 'admin': 'adminT', 'public': 'publicT', 'default': 't' } for (const [key, sig] of Object.entries(signatureMap)) { if (filename?.includes(key)) { return baseResolver(context, sig) } } return baseResolver(context, signatureMap.default) } }) ``` -------------------------------- ### Base Resolver Logic Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/expression-parsing.md Illustrates the logic for the base resolver, which prefixes identifiers based on scope (setup, component, or global). ```typescript const baseResolver = (context, signature) => { // For setup scope: add '$setup.' prefix // For component scope: add '_ctx.' prefix // For global: use as-is return `${contextPrefix}${signature}` } ``` -------------------------------- ### Pre-Translation with i18n Instance Example Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/api-reference/transformVTDirective.md Shows how to create a transform that pre-translates messages at build time using a provided i18n instance. The compiled code will embed translated strings directly, reducing runtime overhead. ```typescript import { compile } from '@vue/compiler-dom' import { createI18n } from 'vue-i18n' import { transformVTDirective } from '@intlify/vue-i18n-extensions' const i18n = createI18n({ locale: 'en', messages: { en: { greeting: 'Hello, {name}!', farewell: 'Goodbye!' }, ja: { greeting: 'こんにちは、{name}!', farewell: 'さようなら!' } } }) const transformVT = transformVTDirective({ i18n }) const source = `
` const { code } = compile(source, { mode: 'function', hoistStatic: true, prefixIdentifiers: true, directiveTransforms: { t: transformVT } }) // The compiled code now contains the string 'Goodbye!' directly // with no runtime translation overhead for this constant ``` -------------------------------- ### Composition Mode Code Generation Example Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/expression-parsing.md Generates code for the Composition API, showing the structure of the translated call with function callable, path, named args, and options. ```javascript // Template:
// Generated code: ($setup.t || t || $t)('greeting', { name: 'John' }, { locale: 'en' }) ``` -------------------------------- ### Nested Args Example in Vue Template Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/expression-parsing.md Demonstrates how to use nested objects within the 'args' property of a v-t expression in a Vue template. ```vue
``` -------------------------------- ### TransformVTDirectiveOptions Usage Examples Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/types.md Demonstrates how to use the TransformVTDirectiveOptions interface with explicit generic parameters for type safety, and a simpler version without generics for more permissive configuration. ```typescript import { TransformVTDirectiveOptions } from '@intlify/vue-i18n-extensions' import type { I18n } from 'vue-i18n' // Type-safe options with explicit generic parameters const options: TransformVTDirectiveOptions< { greeting: string }, {}, {}, false > = { i18n: myI18nInstance, mode: 'composition', translationSignatures: 't' } // Without generics (more permissive) const simpleOptions: TransformVTDirectiveOptions = { mode: 'composition' } ``` -------------------------------- ### Legacy Mode Code Generation Examples Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/expression-parsing.md Generates code for the legacy $t/$tc API, illustrating basic calls, calls with arguments, and calls with pluralization. ```javascript // Template:
// Generated: $_i18n.$t('greeting') or $t('greeting') // With args // Generated: $_i18n.$t('greeting', undefined, { name: 'John' }) // With plural // Generated: $_i18n.$tc('apples', 2) ``` -------------------------------- ### Unsupported Ternary/Conditional Expression Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/directive-syntax-reference.md Shows an example of an unsupported ternary or conditional expression used with the v-t directive. ```vue
``` -------------------------------- ### Correcting NOT_RESOLVED_COMPOSER Setup Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/errors.md Shows the correct way to initialize the i18n instance and pass it to transformVTDirective to prevent NOT_RESOLVED_COMPOSER errors. Ensure a valid vue-i18n instance is created and provided. ```typescript import { createI18n } from 'vue-i18n' import { transformVTDirective } from '@intlify/vue-i18n-extensions' // Correct way to create i18n instance const i18n = createI18n({ locale: 'en', messages: { /* ... */ } }) // Pass the proper i18n instance const transformVT = transformVTDirective({ i18n }) ``` -------------------------------- ### Composition Mode Plural Handling Example Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/configuration.md Demonstrates how pluralization is handled in Composition API mode. The `t()` function is used with an options object for pluralization. ```javascript // Input:
// Output: (t)('apple', {}, { plural: 5 }) ``` -------------------------------- ### v-t Directive Member Expression Example Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/README.md Illustrates the use of the `v-t` directive with a member expression to access a translation key. ```html

``` -------------------------------- ### Legacy Mode Plural Handling Example Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/configuration.md Demonstrates how pluralization is handled in Legacy API mode. The `$tc()` method is used to handle pluralization with the count. ```javascript // Input:
// Output: $_i18n.$tc('apple', 5) or $tc('apple', 5) ``` -------------------------------- ### Pluralization Usage Examples Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/directive-syntax-reference.md Demonstrates how the v-t directive selects different plural forms based on the 'plural' argument. The output changes according to whether the count is zero, one, or more. ```vue
``` -------------------------------- ### Initialize transformVTDirective Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/api-summary.md Initializes the transformVTDirective function without any specific options. This is the basic setup for enabling Vue-i18n extensions. ```typescript const transformVT = transformVTDirective() ``` -------------------------------- ### Fixing Unexpected Directive Expression Errors Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/errors.md Provides correct examples for v-t directive usage to avoid the UNEXPECTED_DIRECTIVE_EXPRESSION error. ```vue
``` -------------------------------- ### Unsupported Expression Types Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/expression-parsing.md Examples of expression types that are not supported by the v-t directive and will result in NOT_SUPPORTED errors. ```vue
``` -------------------------------- ### SSR Setup for Vite Configuration Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/integration-guide.md Configure Vite for Server-Side Rendering (SSR) by using `transformVTDirective` with `mode: 'composition'` and marking 'vue-i18n' as external. Pre-translation can be handled at runtime on the server. ```typescript // vite.config.ts (SSR mode) import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import { transformVTDirective } from '@intlify/vue-i18n-extensions' // Transform without pre-translation for SSR // Pre-translation can be done at runtime on the server const transformVT = transformVTDirective({ mode: 'composition' }) export default defineConfig({ ssr: { external: ['vue-i18n'] // Mark as external in SSR bundle }, plugins: [ vue({ template: { compilerOptions: { directiveTransforms: { t: transformVT } } } }) ] }) ``` -------------------------------- ### Safe Evaluation Examples Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/expression-parsing.md Illustrates safe evaluation scenarios for string literals and object expressions, contrasting them with unsupported types like variable references and function calls. ```javascript // ✓ String literal 'greeting' → 'greeting' // ✓ Object with literal values { path: 'greeting', locale: 'en' } → { path: 'greeting', locale: 'en' } // ✓ Object with string literals { path: 'msg.greeting', args: { name: 'John' } } → { path: 'msg.greeting', args: { name: 'John' } } // ✗ Variable reference (cannot evaluate) translationKey → fails // ✗ Function call (not allowed) getMessage() → fails ``` -------------------------------- ### Fixing Required Parameter Errors Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/errors.md Provides correct examples for v-t directive usage, ensuring the 'path' property is included in object values to avoid the REQUIRED_PARAMETER error. ```vue
``` -------------------------------- ### Internal Usage: Generating Composable Code Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/api-reference/createContentBuilder.md An internal example showing how createContentBuilder is used within the vue-i18n-extensions library to generate translation function calls with proper formatting. ```typescript // Internal example from transform.ts function generateComposableCode(context, params, translationSignatures) { const builder = createContentBuilder() builder.push(`(${signatureCode}) builder.push(`)`) builder.push(`${toDisplayString(params.path)}`) builder.push(`, { `) // ... add named parameters builder.push(` }`) builder.push(`, { `) // ... add options builder.push(` }`) builder.push(`)`) return builder.content } ``` -------------------------------- ### Handling NOT_RESOLVED_COMPOSER Errors Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/errors.md This example illustrates how to handle NOT_RESOLVED_COMPOSER errors. This error occurs when the i18n instance provided to transformVTDirective is invalid or lacks a proper global composer. ```typescript import { ReportCodes } from '@intlify/vue-i18n-extensions' // Triggers when i18n instance is invalid: const transformVT = transformVTDirective({ i18n: someInvalidObject // Not a proper I18n instance }) ``` -------------------------------- ### SSR without Pre-Translation Example Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/api-reference/transformVTDirective.md Demonstrates how to create a transform that generates SSR-compatible code without pre-translating messages. This code is compiled using Vue's compiler with the custom directive transform. ```typescript import { compile } from '@vue/compiler-dom' import { transformVTDirective } from '@intlify/vue-i18n-extensions' const transformVT = transformVTDirective() const source = `
` const { code } = compile(source, { mode: 'function', directiveTransforms: { t: transformVT } }) // The code variable now contains optimized template code that calls // the translation function at render time ``` -------------------------------- ### Build Project Source: https://github.com/intlify/vue-i18n-extensions/blob/next/CONTRIBUTING.md Build all distribution files, including npm packages. ```bash pnpm build ``` -------------------------------- ### Run Full Test Suite Source: https://github.com/intlify/vue-i18n-extensions/blob/next/CONTRIBUTING.md Execute the complete test suite, including linting and unit tests. ```bash pnpm test ``` -------------------------------- ### Run Unit Tests Source: https://github.com/intlify/vue-i18n-extensions/blob/next/CONTRIBUTING.md Execute unit tests for the project. ```bash pnpm test:unit ``` -------------------------------- ### Configure transformVTDirective for Composition API Mode Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/configuration.md Sets the i18n mode to 'composition' for generating translation code using the Composition API style with the `t()` function from `useI18n()`. This is the default mode and is suitable for Vue 3 with ` // ``` -------------------------------- ### Pre-translate with v-t Directive using @vue/compiler-dom Source: https://github.com/intlify/vue-i18n-extensions/blob/next/README.md Configure the Vue compiler to use the `v-t` directive for pre-translation. This example demonstrates integrating with `@vue/compiler-dom` and shows the generated code output. ```javascript import { compile } from '@vue/compiler-dom' import { createI18n } from 'vue-i18n' import { transformVTDirective } from '@intlify/vue-i18n-extensions' // create i18n instance const i18n = createI18n({ locale: 'ja', messages: { en: { hello: 'hello' }, ja: { hello: 'こんにちは' } } }) // get transform from `transformVTDirective` function, with `i18n` option const transformVT = transformVTDirective({ i18n }) const { code } = compile(`

`, { mode: 'function', hoistStatic: true, prefixIdentifiers: true, directiveTransforms: { t: transformVT } // <- you need to specify to `directiveTransforms` option! }) console.log(code) /* output -> const { createVNode: _createVNode, openBlock: _openBlock, createBlock: _createBlock } = Vue return function render(_ctx, _cache) { return (_openBlock(), _createBlock(\"div\", null, \"こんにちは!\")) } */ ``` -------------------------------- ### Lint Source Codes Source: https://github.com/intlify/vue-i18n-extensions/blob/next/CONTRIBUTING.md Check source code for style and potential errors using ESLint. ```bash pnpm lint ``` -------------------------------- ### Composition vs Legacy API Output Comparison Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/directive-syntax-reference.md Compares the generated JavaScript output for the same v-t directive input between the Composition API and the Legacy API. ```vue
``` ```javascript (t)('greeting', { name: 'John' }, { plural: 2 }) ``` ```javascript $tc('greeting', 2) Note: Legacy API uses `$tc` for plural, doesn't include named args in this example. ``` -------------------------------- ### createContentBuilder() Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/api-summary.md Creates a builder instance for constructing formatted code strings with indentation. It provides methods to append content, add newlines, and manage indentation levels. ```APIDOC ## createContentBuilder() ### Description Creates a builder instance for constructing formatted code strings. This utility helps in generating multi-line code with proper indentation. ### Method ``` function createContentBuilder(options?: ContentBuilderOptions): ContentBuilder ``` ### Parameters #### Options - **indentLevel?** (number) - Optional - Initial indent level (default: 0). ### Returns Builder instance for constructing formatted code strings. ### Key Methods - **push(content: string)**: Append content. - **newline()**: Add newline with current indentation. - **indent(withoutNewLine?: boolean)**: Increase indentation level. - **deindent(withoutNewLine?: boolean)**: Decrease indentation level. ``` -------------------------------- ### Template Generation with createContentBuilder Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/api-reference/createContentBuilder.md Shows how to generate template code, like a Vue render function, using createContentBuilder to manage nested calls and string literals. ```typescript const builder = createContentBuilder() builder.push('const render = () => (') builder.indent() builder.pushline("createElement('div', [") builder.indent() builder.pushline("createElement('p', null, 'Hello'),") builder.pushline("createElement('p', null, 'World')") builder.deindent() builder.pushline('])') builder.deindent() builder.push(')') console.log(builder.content) ``` -------------------------------- ### Simple Named Parameter Usage Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/directive-syntax-reference.md Use the 'args' object in the v-t directive to pass simple named parameters for string interpolation. The 'path' specifies the translation key, and 'args' provides the values. ```vue
``` -------------------------------- ### ContentBuilderOptions Interface Definition Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/types.md Specifies the options available for initializing a `ContentBuilder` instance. Currently, it only supports setting the initial indentation level. ```typescript export interface ContentBuilderOptions { indentLevel?: number } ``` -------------------------------- ### Shared i18n Configuration for Pre-Translation Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/integration-guide.md Define a shared i18n configuration file for pre-translation. This allows the i18n instance to be created outside the build process and reused. ```typescript // i18n.config.ts - shared configuration import { createI18n } from 'vue-i18n' export const createI18nInstance = () => createI18n({ legacy: false, locale: 'en', messages: { en: { hello: 'Hello', greeting: 'Hello, {name}!', apples: 'no apples | one apple | {count} apples' }, ja: { hello: 'こんにちは', greeting: 'こんにちは、{name}!', apples: 'りんごはありません | 1つのりんご | {count}個のりんご' } } }) ``` -------------------------------- ### Unsupported Arithmetic/Logical Expressions Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/directive-syntax-reference.md Illustrates unsupported arithmetic and logical expressions within the v-t directive. ```vue
``` -------------------------------- ### Object with Variable Properties - Variable Path and Literal Options - Generated Code Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/directive-syntax-reference.md Generated code for a variable path with literal options. ```javascript (t)(messageKey, {}, { locale: 'ja' }) ``` -------------------------------- ### Configure Vite Plugin Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/configuration.md Set up the transformVTDirective for Vite projects using the @vitejs/plugin-vue. This allows for custom directive transformations. ```javascript import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import { transformVTDirective } from '@intlify/vue-i18n-extensions' const transformVT = transformVTDirective({ /* options */ }) export default defineConfig({ plugins: [ vue({ template: { compilerOptions: { directiveTransforms: { t: transformVT } } } }) ] }) ``` -------------------------------- ### Basic String Path Translation Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/integration-guide.md Use the `v-t` directive with a simple string path to display translated text. This is the most basic form of template usage for translations. ```vue ``` -------------------------------- ### Object with Nested Args - Simple Nested Args - Generated Code Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/directive-syntax-reference.md Generated Composition API code for passing simple nested arguments. ```javascript (t)('user.greeting', { user: { name: 'Jane', title: 'Dr.' } }, {}) ``` -------------------------------- ### Using Indent Without Newline with createContentBuilder Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/api-reference/createContentBuilder.md Demonstrates the use of `indent(true)` and `deindent(true)` to control indentation levels without automatically adding newlines, useful for precise formatting of configuration objects. ```typescript const builder = createContentBuilder() builder.push('export const config = {') builder.indent(true) // Increase indent level without newline builder.newline() builder.push('locale: "en",') builder.newline() builder.push('messages: {}') builder.deindent(true) // Decrease indent level without newline builder.newline() builder.push('}') console.log(builder.content) ``` -------------------------------- ### Variable Reference - Generated Code Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/directive-syntax-reference.md Illustrates the generated code for variable references, applicable to both Composition and legacy APIs. ```javascript (t)(translationKey, {}, {}) ``` ```javascript $t(translationKey) ``` -------------------------------- ### Vue Template Directives for Pre-translation Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/integration-guide.md Illustrates Vue template syntax for pre-translation. Shows a dynamic expression that won't be pre-translated and a constant expression that will. ```vue
``` -------------------------------- ### Lazy-loading Messages for Build Performance Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/integration-guide.md Demonstrates splitting large message sets by using a function to load static messages, potentially improving build performance. Assumes `loadStaticMessages` is defined elsewhere. ```typescript // Split large message sets const i18n = createI18n({ legacy: false, locale: 'en', messages: { en: loadStaticMessages() // Only load frequently-used messages } }) ``` -------------------------------- ### Building Nested Structures with createContentBuilder Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/api-reference/createContentBuilder.md Illustrates creating nested code structures, such as object literals with nested arrays, using the indent and deindent methods of createContentBuilder. ```typescript const builder = createContentBuilder() builder.push('const obj = {') builder.indent() builder.pushline("name: 'test',") builder.pushline('values: [') builder.indent() builder.pushline('1,') builder.pushline('2,') builder.pushline('3') builder.deindent() builder.pushline(']') builder.deindent() builder.push('}') console.log(builder.content) ``` -------------------------------- ### Push Raw Content to Builder Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/api-reference/createContentBuilder.md Appends text directly to the builder's content without adding newlines or indentation. Use when precise control over formatting is needed. ```typescript const builder = createContentBuilder() builder.push('const greeting = ') builder.push('"hello"') console.log(builder.content) // Output: const greeting = "hello" ``` -------------------------------- ### Unsupported Template String Expression Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/directive-syntax-reference.md Demonstrates an unsupported use case of a template string as the primary expression for the v-t directive. ```vue
``` -------------------------------- ### Transform VT Directive with Custom Resolvers Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/types.md Demonstrates how to use `transformVTDirective` with custom translation signature resolvers. This allows for dynamic selection of translation functions based on context, such as filename or available bindings. ```typescript import { transformVTDirective } from '@intlify/vue-i18n-extensions' import type { TranslationSignatureResolver } from '@intlify/vue-i18n-extensions' import type { TransformContext } from '@vue/compiler-dom' // Simple resolver that checks filename const filenameResolver: TranslationSignatureResolver = (context, baseResolver) => { const { filename } = context if (filename?.includes('admin')) { return baseResolver(context, 'adminT') } return baseResolver(context, 't') } // Resolver with custom logic const customResolver: TranslationSignatureResolver = (context, baseResolver) => { const { prefixIdentifiers, bindingMetadata } = context // Check if 'useI18nTranslate' is available in bindings if ('useI18nTranslate' in bindingMetadata) { return baseResolver(context, 'useI18nTranslate') } // Fallback to standard signature return baseResolver(context, 't') } const transformVT = transformVTDirective({ translationSignatures: [filenameResolver, customResolver, 't'] }) ``` -------------------------------- ### Default Locale Usage Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/directive-syntax-reference.md Demonstrates the default behavior of the v-t directive, which uses the current locale from the i18n instance. ```vue
``` -------------------------------- ### Configure vue-loader for v-t Directive Pre-translation Source: https://github.com/intlify/vue-i18n-extensions/blob/next/README.md Set up `vue-loader` to enable pre-translation using the `v-t` directive by configuring `compilerOptions.directiveTransforms`. Ensure `VueLoaderPlugin` is included. ```javascript const { VueLoaderPlugin } = require('vue-loader') const { createI18n } = require('vue-i18n') const { transformVTDirective } = require('@intlify/vue-i18n-extensions') const i18n = createI18n({ locale: 'ja', messages: { en: { hello: 'hello' }, ja: { hello: 'こんにちは' } } }) const transformVT = transformVTDirective(i18n) module.exports = { module: { // ... rules: [ { test: /\.vue$/, use: [ { loader: 'vue-loader', options: { compilerOptions: { directiveTransforms: { t: transformVT } } } } ] } // ... ] }, plugins: [new VueLoaderPlugin()], parallel: false // the compilerOptions.directiveTransforms are not serializable } ``` -------------------------------- ### Configure Array of String Translation Signatures Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/configuration.md Provide an array of strings to define multiple custom translation function names. They are tried in order, with '$t' as the final fallback. ```typescript const transformVT = transformVTDirective({ translationSignatures: ['useI18nT', 'customT', 't'] // Tries in order: useI18nT, customT, t, $t (fallback) }) ``` -------------------------------- ### Babel Parser Usage Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/expression-parsing.md Demonstrates using @babel/parser to safely analyze JavaScript expressions within the v-t directive. It handles all JavaScript syntax and provides a structured AST. ```typescript import { parse } from '@babel/parser' // Parse v-t expression const ast = parse(`const a = ${expression.trim()}`) ``` -------------------------------- ### String Literal Path - Generated Code Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/directive-syntax-reference.md Shows the generated code for string literal paths using both Composition API and legacy API. ```javascript (t)('greeting', {}, {}) ``` ```javascript $t('greeting') ``` -------------------------------- ### Vite Configuration with Pre-Translation Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/integration-guide.md Configure Vite to use the VT directive transform, optionally with pre-translation. This involves setting up `vue` plugin with `compilerOptions` and creating an i18n instance. ```typescript // vite.config.ts import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import { createI18n } from 'vue-i18n' import { transformVTDirective } from '@intlify/vue-i18n-extensions' // Create i18n instance for pre-translation const i18n = createI18n({ legacy: false, locale: 'en', messages: { en: { greeting: 'Hello, {name}!', farewell: 'Goodbye!' }, ja: { greeting: 'こんにちは、{name}!', farewell: 'さようなら!' } } }) // Create transform with pre-translation const transformVT = transformVTDirective({ i18n }) export default defineConfig({ plugins: [ vue({ template: { compilerOptions: { directiveTransforms: { t: transformVT } } } }) ] }) ``` -------------------------------- ### Initialize transformVTDirective with Dynamic Translation Signature Resolver Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/api-summary.md Initializes the transformVTDirective function with a dynamic resolver for translation signatures. This allows for custom logic to determine the translation function name based on the context. ```typescript const transformVT = transformVTDirective({ translationSignatures: (context, baseResolver) => { // custom logic return baseResolver(context, 't') } }) ``` -------------------------------- ### Vite Configuration with Shared i18n Instance Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/integration-guide.md Configure Vite to use a shared i18n instance for pre-translation. This involves importing the instance from a separate configuration file and passing it to `transformVTDirective`. ```typescript // vite.config.ts import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import { transformVTDirective } from '@intlify/vue-i18n-extensions' import { createI18nInstance } from './src/i18n.config' const i18n = createI18nInstance() const transformVT = transformVTDirective({ i18n }) export default defineConfig({ plugins: [ vue({ template: { compilerOptions: { directiveTransforms: { t: transformVT } } } }) ] }) ``` -------------------------------- ### Object with Choice (Plural) Syntax Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/directive-syntax-reference.md Shows how to use the 'choice' property as an alias for 'plural' in the v-t directive for pluralization. ```vue
``` ```vue
``` ```javascript (t)('items', {}, { plural: 2 }) // Composition $tc('items', 2) // Legacy ``` -------------------------------- ### Append Line with Automatic Newline and Indentation Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/api-reference/createContentBuilder.md Combines pushing content and adding a newline with automatic indentation. This is a convenient shortcut for common line-based content. ```typescript const builder = createContentBuilder() builder.pushline('const x = 1') builder.pushline('const y = 2') console.log(builder.content) // Output: // const x = 1 // const y = 2 ``` -------------------------------- ### Object with Variable Properties - Variable Path and Variable Locale - Generated Code Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/directive-syntax-reference.md Generated code for a variable path with a variable locale. ```javascript (t)(msgKey, {}, { locale: currentLocale }) ``` -------------------------------- ### Evaluable Expressions for Pre-Translation Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/directive-syntax-reference.md Lists expressions that can be pre-translated by the i18n instance, including string literals and objects with literal values. ```vue
``` -------------------------------- ### Object Literal - All Options Combined - Generated Code Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/directive-syntax-reference.md Generated Composition API code for an object literal with all options combined. ```javascript (t)('fruit.count', { fruit: 'apple' }, { locale: 'en', plural: 3 }) ``` -------------------------------- ### String Literal Path Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/directive-syntax-reference.md Use a simple string literal for direct translation paths. This is pre-translatable if i18n is provided. ```vue
``` -------------------------------- ### Valid Object Syntax with Required Path Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/directive-syntax-reference.md Shows a valid usage of the v-t directive with object syntax, including the required 'path' property. ```vue
``` ```vue
``` -------------------------------- ### Object with Nested Args - Simple Nested Args Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/directive-syntax-reference.md Pass nested objects as named arguments to the translation. The message template can then reference these nested properties. ```vue
``` -------------------------------- ### TypeScript Configuration with Type Safety Source: https://github.com/intlify/vue-i18n-extensions/blob/next/_autodocs/integration-guide.md Sets up a type-safe i18n instance and transform directive using TypeScript. Defines message schema and configures `vue-i18n` with messages. ```typescript // i18n.config.ts import { createI18n } from 'vue-i18n' import { transformVTDirective } from '@intlify/vue-i18n-extensions' // Define message structure type MessageSchema = { greeting: string farewell: string apples: string } // Type-safe i18n instance const i18n = createI18n({ legacy: false, locale: 'en', messages: { en: { greeting: 'Hello', farewell: 'Goodbye', apples: 'no apples | one apple | {count} apples' } } }) // Type-safe transform const transformVT = transformVTDirective({ i18n, mode: 'composition' }) export { i18n, transformVT } ```