Skip to content

Commit 558f7d9

Browse files
authored
docs: usage page rework (#3509)
* docs: rework usage page * docs: add page detailing vue-i18n config
1 parent e8e8d15 commit 558f7d9

2 files changed

Lines changed: 139 additions & 64 deletions

File tree

docs/content/docs/01.getting-started/02.usage.md

Lines changed: 88 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -1,144 +1,167 @@
11
---
22
title: Usage
3-
description: The basics to get started with the Nuxt i18n module is to translate with Vue I18n via the `vueI18n` option.
3+
description: The basics to get started with the Nuxt i18n module
44
---
55

6-
## Translate with Vue I18n
6+
## Basic setup
77

8-
The basics to get started with **Nuxt i18n module** is to **translate with Vue I18n via the `vueI18n` option**
8+
Let's start by configuring the project `locales` and the `defaultLocale` in the nuxt config.
9+
10+
For this project we configure the locales with the following properties:
11+
12+
- `code`: required property, the locale code is used throughout Nuxt I18n and is used as the identifier for the locale.
13+
- `name`: name of the locale, this is a user-friendly way to identify the locale.
14+
- `file`: a file that provides translation messages in the form of an object.
15+
16+
The `defaultLocale` should be set to the `code` of one of the configured locales, setting this is optional but recommended as it will be used as fallback when navigating to a non-existent route.
917

1018
```ts [nuxt.config.ts]
1119
export default defineNuxtConfig({
1220
modules: ['@nuxtjs/i18n'],
1321
i18n: {
14-
vueI18n: './i18n.config.ts' // if you are using custom path, default
22+
defaultLocale: 'en',
23+
locales: [
24+
{ code: 'en', name: 'English', file: 'en.json' },
25+
{ code: 'nl', name: 'Nederlands', file: 'nl.json' }
26+
]
1527
}
1628
})
1729
```
1830

19-
```ts [i18n/i18n.config.ts]
20-
export default defineI18nConfig(() => ({
21-
legacy: false,
22-
locale: 'en',
23-
messages: {
24-
en: {
25-
welcome: 'Welcome'
26-
},
27-
fr: {
28-
welcome: 'Bienvenue'
29-
}
30-
}
31-
}))
31+
A typical project has at least one `file` for each configured locale, this file provides the translation messages in the form of an object.
32+
33+
Nuxt I18n has a (configurable) folder structure from which the locale files are sourced, the locale files should be created in `<rootDir>/i18n/locales` by default.
34+
35+
::code-group
36+
37+
```json [i18n/locales/en.json]
38+
{
39+
"welcome": "Welcome"
40+
}
3241
```
3342

34-
The `i18n.config` file exports the same options as the `createI18n`{lang="ts-type"} function of Vue I18n. The configuration is passed to the `createI18n` function via the Nuxt plugin (runtime) of this module internally. For more details about configuration, see the [Vue I18n documentation](https://vue-i18n.intlify.dev/api/general.html#createi18n).
43+
```json [i18n/locales/nl.json]
44+
{
45+
"welcome": "Welkom"
46+
}
47+
```
3548

36-
::callout{icon="i-heroicons-light-bulb"}
37-
The following documentation explains how to use the Nuxt i18n module using Vue I18n Composition API. :br
38-
For more information on how to use Vue I18n Composition API, please see the docs [here](https://vue-i18n.intlify.dev/guide/advanced/composition.html).
3949
::
4050

41-
Now, put (or edit) the following the page component in `pages` directory of your project:
51+
With this configuration we can add a basic language switcher and translate our first message using:
4252

53+
<!-- prettier-ignore -->
4354
```vue [pages/index.vue]
4455
<script setup>
45-
const { setLocale } = useI18n()
56+
const { locales, setLocale } = useI18n()
4657
</script>
4758
4859
<template>
4960
<div>
50-
<div>
51-
<button @click="setLocale('en')">en</button>
52-
<button @click="setLocale('fr')">fr</button>
53-
<p>{{ $t('welcome') }}</p>
54-
</div>
61+
<button v-for="locale in locales" @click="setLocale(locale.code)">
62+
{{ locale.name }}
63+
</button>
64+
<h1>{{ $t('welcome') }}</h1>
5565
</div>
5666
</template>
5767
```
5868

59-
You now have a really simple Vue I18n based translation environment ready to go! The `<button>` elements can be used to switch between the English and French languages, by clicking either of the buttons you can see the word "welcome" translate and the page URL change to its corresponding language.
69+
Using the configured locales we created a simple language-switcher, by clicking a `<button>` element you can switch between English and Dutch and see the "welcome" message and page URL change to its corresponding language.
6070

61-
::callout{icon="i-heroicons-light-bulb"}
62-
For more information about **Vue I18n**, you can refer to its documentation [here](https://vue-i18n.intlify.dev/).
63-
::
71+
You now have a basic setup to get started with fully localizing your Nuxt Application!
6472

6573
## Auto Imports
6674

67-
Some composable functions provided by `@nuxtjs/i18n` such as `useI18n` are [auto-imported by Nuxt](https://nuxt.com/docs/guide/concepts/auto-imports#auto-imports).
68-
If you want to import them explicitly, you can use `#imports` as follows:
75+
Some composable functions such as `useI18n` are [auto-imported by Nuxt](https://nuxt.com/docs/guide/concepts/auto-imports#auto-imports).
76+
If you have disabled `autoImports` you will need to import these explicitly from `#imports` as follows:
6977

78+
<!-- prettier-ignore -->
7079
```vue
7180
<script setup>
7281
import { useI18n, useLocalePath } from '#imports'
7382
// ...
7483
</script>
7584
```
7685

77-
## Link localizing
78-
79-
The **Nuxt i18n module** extends the integrated Vue I18n to give us some i18n features for Nuxt application. In here, we introduce one of those features, the link localization with extending Nuxt pages and routing.
86+
## Route localization
8087

81-
### Configurations
88+
Nuxt I18n generates localized routes for each locale, in the most basic setup this comes in the form of a prefixed variant of each route with a locale code.
8289

83-
You'll need to additionally set the `defaultLocale` and `locales` options, as in the following configuration.
90+
When linking to routes within your app, you will need to get the localized route for the current locale. This is done with utility functions provided by Nuxt I18n.
8491

85-
For localizing links, you can use the code provided from the `locales` option as the URL path prefix, except for `defaultLocale` (read more on [routing](/docs/guide)).
92+
### Resolving a localized route with `$localePath`
8693

87-
```diff [nuxt.config.ts]
88-
export default defineNuxtConfig({
89-
modules: ['@nuxtjs/i18n'],
94+
The `$localePath` function is used to get the localized route for a given route, this function is returned by `useLocalePath` for usage outside `<template>`.
9095

91-
i18n: {
92-
+ locales: ['en', 'fr'], // used in URL path prefix
93-
+ defaultLocale: 'en', // default locale of your project for Nuxt pages and routings
94-
}
95-
})
96-
```
96+
This function accepts two parameters:
9797

98-
When rendering internal links in your app using `<NuxtLink>`, you need to get proper URLs for the current locale. To do this, the **Nuxt i18n module** provides some helper composables:
98+
- `route`: name of a route or a route object with a name property
99+
- `locale`: locale code in which the route should be localized, defaults to the current locale
99100

100-
### URL path
101+
::code-group
101102

102-
You can localize URL paths using `useLocalePath`.
103-
104-
`useLocalePath` is a composable which returns a function used to get the localized URL for a given path. The first parameter can either be the path or name of the route or an object for more complex routes. A locale code can be passed as the second parameter to generate a link for a specific language:
103+
<!-- prettier-ignore -->
104+
```vue [page.vue (global function)]
105+
<template>
106+
<NuxtLink :to="$localePath('index')">{{ $t('home') }}</NuxtLink>
107+
<NuxtLink :to="$localePath('index', 'en')">Homepage in English</NuxtLink>
108+
<NuxtLink :to="$localePath('user-profile')">Route to {{ $t('profile') }}</NuxtLink>
109+
<NuxtLink :to="$localePath({ name: 'category-slug', params: { slug: category.slug } })">
110+
{{ category.title }}
111+
</NuxtLink>
112+
</template>
113+
```
105114

106-
```vue
115+
<!-- prettier-ignore -->
116+
```vue [page.vue (composable)]
107117
<script setup>
108118
const localePath = useLocalePath()
109119
</script>
110120
111121
<template>
112122
<NuxtLink :to="localePath('index')">{{ $t('home') }}</NuxtLink>
113-
<NuxtLink :to="localePath('/')">{{ $t('home') }}</NuxtLink>
114123
<NuxtLink :to="localePath('index', 'en')">Homepage in English</NuxtLink>
115-
<NuxtLink :to="localePath('/user/profile')">Route by path to: {{ $t('profile') }}</NuxtLink>
116-
<NuxtLink :to="localePath('user-profile')">Route by name to: {{ $t('profile') }}</NuxtLink>
124+
<NuxtLink :to="localePath('user-profile')">Route to {{ $t('profile') }}</NuxtLink>
117125
<NuxtLink :to="localePath({ name: 'category-slug', params: { slug: category.slug } })">
118126
{{ category.title }}
119127
</NuxtLink>
120128
</template>
121129
```
122130

123-
Note that `localePath` can use the route's unprefixed path, which must start with `'/'` or the route's base name to generate the localized URL. The base name corresponds to the names Nuxt generates when parsing your `pages` directory, more info in [Nuxt docs](https://nuxt.com/docs/guide/directory-structure/pages).
131+
::
124132

125-
### Language switching path
133+
Since localized routes can change based on your configuration, using route names ensures accurate resolution. Nuxt I18n generates types to facilitate this, providing type safety and improved developer experience. To utilize these types, enable `typedPages` in your Nuxt configuration.
126134

127-
You can localize the language of the current path using `useSwitchLocalePath`.
135+
The route name corresponds to the names Nuxt generates when parsing your `pages` directory, more info in [Nuxt docs](https://nuxt.com/docs/guide/directory-structure/pages).
128136

129-
`useSwitchLocalePath` is a composable function which returns a link to the current page in another language:
137+
### Switching between languages
130138

131-
```vue
139+
The `$switchLocalePath` function returns the localized version of the route to the current page, it accepts a locale code in which the current route should be localized.
140+
141+
::code-group
142+
143+
<!-- prettier-ignore -->
144+
```vue [page.vue (global function)]
145+
<template>
146+
<NuxtLink :to="$switchLocalePath('en')">English</NuxtLink>
147+
<NuxtLink :to="$switchLocalePath('nl')">Nederlands</NuxtLink>
148+
</template>
149+
```
150+
151+
<!-- prettier-ignore -->
152+
```vue [page.vue (composable)]
132153
<script setup>
133154
const switchLocalePath = useSwitchLocalePath()
134155
</script>
135156
136157
<template>
137158
<NuxtLink :to="switchLocalePath('en')">English</NuxtLink>
138-
<NuxtLink :to="switchLocalePath('fr')">Français</NuxtLink>
159+
<NuxtLink :to="switchLocalePath('nl')">Nederlands</NuxtLink>
139160
</template>
140161
```
141162

163+
::
164+
142165
### URL path with Route object
143166

144167
You can localize advanced URL paths using `useLocaleRoute`. This is useful if you would to control internal links programmatically.
@@ -147,6 +170,7 @@ You can localize advanced URL paths using `useLocaleRoute`. This is useful if yo
147170

148171
It works like `useLocalePath` but returns a route resolved by Vue Router rather than a full route path. This can be useful as the path returned from `useLocalePath` may not carry all information from the provided input (for example, route params that the page doesn't specify).
149172

173+
<!-- prettier-ignore -->
150174
```vue
151175
<script setup>
152176
const localeRoute = useLocaleRoute()
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
---
2+
title: Vue I18n Configuration
3+
description: Configuring runtime options for Vue I18n
4+
---
5+
6+
## Vue I18n Configuration
7+
8+
While some options are shared between Nuxt I18n and Vue I18n, there is a range of options which are specific to Vue I18n, for example:
9+
10+
- `fallbackWarn`: To ontrol fallback warnings.
11+
- `missingWarn`: To control missing localization warnings.
12+
- `formatter`: To provide a custom message formatting function.
13+
- `numberFormats`: To configure custom number formatting.
14+
- `datetimeFormats`: To configure custom date time formatting.
15+
- ... more!
16+
17+
These are just a few examples of the runtime options available in Vue I18n, please check out [the documentation of Vue I18n](https://vue-i18n.intlify.dev/) to explore the full range of available options.
18+
19+
Vue I18n specific options cannot be configured in `nuxt.config` and have no overlap with the features used by or provided by Nuxt I18n.
20+
21+
## Adding a Vue I18n config file
22+
23+
To configure the options you can create a `i18n.config.ts` file in the `<rootDir>/i18n` directory, this file should have a default export with a function returning the Vue I18n options.
24+
25+
Nuxt I18n provides a macro function `defineI18nConfig` to improve the types, but a plain function would suffice too:
26+
27+
```ts [i18n/i18n.config.ts]
28+
export default defineI18nConfig(() => {
29+
return {
30+
// vue-i18n options
31+
}
32+
})
33+
```
34+
35+
The config file is resolved from `<rootDir>/i18n`, and automatically looks for and loads the config file using the default filename of `i18n.config`. This can be configured using the `vueI18n` options.
36+
37+
## When to use
38+
39+
Use `i18n.config.ts` when you need to configure Vue I18n options that involve runtime functions or data that cannot be serialized for build-time processing. This is often the case when:
40+
41+
- You need to dynamically load or manipulate localization data based on user input or external APIs.
42+
- You are using custom formatting functions or other non-serializable options.
43+
- You need to use Vue I18n options that are not supported by Nuxt I18n's build-time configuration.
44+
45+
## Nuxt config benefits
46+
47+
While it is possible to configure the same (or functionally the same) options configurable in `nuxt.config.ts` (`messages` - instead of `locales`, `defaultLocale`, etc.) it is recommended to keep as much of the configuration as Nuxt I18n supports on the `i18n` key inside `nuxt.config`.
48+
49+
Nuxt I18n will use these options during the build step and can configure and optimize functionalities by integrating with other libraries such as `@intlify/unplugin-vue-i18n`.
50+
51+
The Vue I18n config file will be loaded at runtime on each request which can increase server response times, especially in high-traffic applications. This is because the server needs to parse and process the configuration for every incoming request and merge them with those set by Nuxt I18n, rather than doing it once at build time.

0 commit comments

Comments
 (0)