Skip to content

Commit

Permalink
feat(docs): Локализация docs/guide/directory-structure/plugins.md (#191)
Browse files Browse the repository at this point in the history
* feat(docs): Локализация docs/guide/directory-structure/plugins.md

* update: docs/2.guide/2.directory-structure/1.plugins.md

Co-authored-by: Bochkarev Ivan <[email protected]>

* update: docs/2.guide/2.directory-structure/1.plugins.md

Co-authored-by: Bochkarev Ivan <[email protected]>

* update: docs/2.guide/2.directory-structure/1.plugins.md

Co-authored-by: Bochkarev Ivan <[email protected]>

* update: docs/2.guide/2.directory-structure/1.plugins.md

Co-authored-by: Bochkarev Ivan <[email protected]>

* update: docs/2.guide/2.directory-structure/1.plugins.md

Co-authored-by: Bochkarev Ivan <[email protected]>

---------

Co-authored-by: Bochkarev Ivan <[email protected]>
  • Loading branch information
mnenie and Ibochkarev authored Jun 18, 2024
1 parent f3237ed commit 9ed4955
Showing 1 changed file with 67 additions and 67 deletions.
134 changes: 67 additions & 67 deletions docs/2.guide/2.directory-structure/1.plugins.md
Original file line number Diff line number Diff line change
@@ -1,36 +1,36 @@
---
title: "plugins"
description: "Nuxt has a plugins system to use Vue plugins and more at the creation of your Vue application."
description: "Nuxt имеет систему плагинов, позволяющую использовать плагины Vue и многое другое при создании вашего Vue приложения."
head.title: "plugins/"
navigation.icon: i-ph-folder-duotone
---

Nuxt automatically reads the files in the `plugins/` directory and loads them at the creation of the Vue application.
Nuxt автоматически считывает файлы из директории `plugins/` и загружает их при создании приложения Vue.

::note
All plugins inside are auto-registered, you don't need to add them to your `nuxt.config` separately.
Все плагины внутри автоматически регистрируются, вам не нужно добавлять их в ваш `nuxt.config` отдельно.
::

::note
You can use `.server` or `.client` suffix in the file name to load a plugin only on the server or client side.
Вы можете использовать суффикс `.server` или `.client` в имени файла, чтобы загрузить плагин только на сервере или клиента.
::

## Registered Plugins
## Зарегистрированные плагины

Only files at the top level of the directory (or index files within any subdirectories) will be auto-registered as plugins.
Только файлы на верхнем уровне директории (или индексные файлы в любых поддиректориях) будут автоматически зарегистрированы как плагины.

```bash [Directory structure]
```bash [Структура директории]
-| plugins/
---| foo.ts // scanned
---| foo.ts // отсканировано
---| bar/
-----| baz.ts // not scanned
-----| foz.vue // not scanned
-----| index.ts // currently scanned but deprecated
-----| baz.ts // не сканируется
-----| foz.vue // не сканируется
-----| index.ts // в настоящее время сканируется, но устарел
```

Only `foo.ts` and `bar/index.ts` would be registered.
Будут зарегистрированы только `foo.ts` и `bar/index.ts`.

To add plugins in subdirectories, you can use the [`plugins`](/docs/api/nuxt-config#plugins-1) option in `nuxt.config.ts`:
Чтобы добавить плагины в поддиректории, вы можете использовать опцию [`plugins`](/docs/api/nuxt-config#plugins-1) в `nuxt.config.ts`:

```ts twoslash [nuxt.config.ts]
export default defineNuxtConfig({
Expand All @@ -41,126 +41,126 @@ export default defineNuxtConfig({
})
```

## Creating Plugins
## Создание плагинов

The only argument passed to a plugin is [`nuxtApp`](/docs/api/composables/use-nuxt-app).
Единственным аргументом, передаваемым плагину, является [`nuxtApp`](/docs/api/composables/use-nuxt-app).

```ts twoslash [plugins/hello.ts]
export default defineNuxtPlugin(nuxtApp => {
// Doing something with nuxtApp
// Делаем что-то с nuxtApp
})
```

### Object Syntax Plugins
### Плагины объектного синтаксиса

It is also possible to define a plugin using an object syntax, for more advanced use cases. For example:
Также можно определить плагин, используя синтаксис объекта, для более сложных случаев использования. Например:

```ts twoslash [plugins/hello.ts]
export default defineNuxtPlugin({
name: 'my-plugin',
enforce: 'pre', // or 'post'
enforce: 'pre', // или 'post'
async setup (nuxtApp) {
// this is the equivalent of a normal functional plugin
// это эквивалент обычного функционального плагина
},
hooks: {
// You can directly register Nuxt app runtime hooks here
// Здесь вы можете напрямую зарегистрировать runtime хуки приложения Nuxt
'app:created'() {
const nuxtApp = useNuxtApp()
// do something in the hook
// сделать что-то в хуке
}
},
env: {
// Set this value to `false` if you don't want the plugin to run when rendering server-only or island components.
// Установите это значение в `false`, если вы не хотите, чтобы плагин запускался при рендеринге только серверных или island компонентов.
islands: true
}
})
```

::tip{icon="i-ph-video-duotone" to="https://www.youtube.com/watch?v=2aXZyXB1QGQ" target="_blank"}
Watch a video from Alexander Lichter about the Object Syntax for Nuxt plugins.
Посмотрите видео от Александра Лихтера об объектном синтаксисе для плагинов Nuxt.
::

::note
If you are using the object-syntax, the properties are statically analyzed to produce a more optimized build. So you should not define them at runtime. :br
For example, setting `enforce: import.meta.server ? 'pre' : 'post'` would defeat any future optimization Nuxt is able to do for your plugins.
Nuxt does statically pre-load any hook listeners when using object-syntax, allowing you to define hooks without needing to worry about order of plugin registration.
Если вы используете объектный синтаксис, свойства анализируются статически, чтобы создать более оптимизированную сборку. Поэтому не следует определять их во время рантайма. :br
Например, установка `enforce: import.meta.server ? 'pre' : 'post'` приведет к невозможности дальнейшей оптимизации, которую Nuxt сможет выполнить для ваших плагинов.
Nuxt статически предварительно загружает все слушатели хуков при использовании объектного синтаксиса, позволяя вам определять хуки, не заботясь о порядке регистрации плагинов.
::

## Registration Order
## Порядок регистрации

You can control the order in which plugins are registered by prefixing with 'alphabetical' numbering to the file names.
Вы можете контролировать порядок регистрации плагинов, добавляя к именам файлов префикс с 'alphabetical' нумерацией.

```bash [Directory structure]
```bash [Структура директории]
plugins/
| - 01.myPlugin.ts
| - 02.myOtherPlugin.ts
```

In this example, `02.myOtherPlugin.ts` will be able to access anything that was injected by `01.myPlugin.ts`.
В этом примере `02.myOtherPlugin.ts` сможет получить доступ ко всему, что было инжектировано `01.myPlugin.ts`.

This is useful in situations where you have a plugin that depends on another plugin.
Это полезно в ситуациях, когда у вас есть плагин, который зависит от другого плагина.

::note
In case you're new to 'alphabetical' numbering, remember that filenames are sorted as strings, not as numeric values. For example, `10.myPlugin.ts` would come before `2.myOtherPlugin.ts`. This is why the example prefixes single digit numbers with `0`.
Если вы впервые знакомы с 'alphabetical' нумерацией, помните, что имена файлов сортируются как строки, а не как числовые значения. Например, `10.myPlugin.ts` будет находиться перед `2.myOtherPlugin.ts`. Вот почему в приведенном примере однозначным числам присваивается префикс `0`.
::

## Loading Strategy
## Стратегия загрузки

### Parallel Plugins
### Параллельные плагины

By default, Nuxt loads plugins sequentially. You can define a plugin as `parallel` so Nuxt won't wait the end of the plugin's execution before loading the next plugin.
По умолчанию Nuxt загружает плагины последовательно. Вы можете определить плагин как `parallel`, тогда Nuxt не будет ждать окончания выполнения плагина перед загрузкой следующего плагина.

```ts twoslash [plugins/my-plugin.ts]
export default defineNuxtPlugin({
name: 'my-plugin',
parallel: true,
async setup (nuxtApp) {
// the next plugin will be executed immediately
// следующий плагин будет выполнен немедленно
}
})
```

### Plugins With Dependencies
### Плагины с зависимостями

If a plugin needs to wait for another plugin before it runs, you can add the plugin's name to the `dependsOn` array.
Если плагину необходимо дождаться запуска другого плагина, вы можете добавить его имя в массив `dependsOn`.

```ts twoslash [plugins/depending-on-my-plugin.ts]
export default defineNuxtPlugin({
name: 'depends-on-my-plugin',
dependsOn: ['my-plugin'],
async setup (nuxtApp) {
// this plugin will wait for the end of `my-plugin`'s execution before it runs
// этот плагин будет ждать окончания выполнения `my-plugin` перед запуском
}
})
```

## Using Composables
## Использование композаблов

You can use [composables](/docs/guide/directory-structure/composables) as well as [utils](/docs/guide/directory-structure/utils) within Nuxt plugins:
Вы можете использовать [композаблы](/docs/guide/directory-structure/composables), а также [утилиты](/docs/guide/directory-structure/utils) в плагинах Nuxt:

```ts [plugins/hello.ts]
export default defineNuxtPlugin((nuxtApp) => {
const foo = useFoo()
})
```

However, keep in mind there are some limitations and differences:
Однако имейте в виду, что существуют некоторые ограничения и различия:

::important
**If a composable depends on another plugin registered later, it might not work.** :br
**Если композабл зависит от другого плагина, зарегистрированного позже, он может не сработать.** :br

Plugins are called in order sequentially and before everything else. You might use a composable that depends on another plugin which has not been called yet.
Плагины вызываются последовательно и перед всем остальным. Вы можете использовать композабл, который зависит от другого плагина, который еще не был вызван.
::

::important
**If a composable depends on the Vue.js lifecycle, it won't work.** :br
**Если композабл зависит от жизненного цикла Vue.js, он не будет работать.** :br

Normally, Vue.js composables are bound to the current component instance while plugins are only bound to [`nuxtApp`](/docs/api/composables/use-nuxt-app) instance.
Обычно композаблы Vue.js привязываются к текущему инстансу компонента, а плагины - только к инстансу [`nuxtApp`](/docs/api/composables/use-nuxt-app).
::

## Providing Helpers
## Предоставление хэлперов

If you would like to provide a helper on the [`NuxtApp`](/docs/api/composables/use-nuxt-app) instance, return it from the plugin under a `provide` key.
Если вы хотите предоставить хэлпер для инстанса [`NuxtApp`](/docs/api/composables/use-nuxt-app), верните его из плагина под ключом `provide`.

::code-group
```ts twoslash [plugins/hello.ts]
Expand All @@ -186,11 +186,11 @@ export default defineNuxtPlugin({
```
::

You can then use the helper in your components:
Затем вы можете использовать этот хэлпер в своих компонентах:

```vue [components/Hello.vue]
<script setup lang="ts">
// alternatively, you can also use it here
// альтернативно, вы также можете использовать его здесь
const { $hello } = useNuxtApp()
</script>
Expand All @@ -202,23 +202,23 @@ const { $hello } = useNuxtApp()
```

::important
Note that we highly recommend using [`composables`](/docs/guide/directory-structure/composables) instead of providing helpers to avoid polluting the global namespace and keep your main bundle entry small.
Обратите внимание, что мы настоятельно рекомендуем использовать [`композаблы`](/docs/guide/directory-structure/composables) вместо предоставления хэлперов, чтобы не загрязнять глобальное пространство имен и сохранить небольшой размер основного бандла.
::

::warning
**If your plugin provides a `ref` or `computed`, it will not be unwrapped in a component `<template>`.** :br
This is due to how Vue works with refs that aren't top-level to the template. You can read more about it [in the Vue documentation](https://ru.vuejs.org/guide/essentials/reactivity-fundamentals.html#caveat-when-unwrapping-in-templates).
**Если ваш плагин предоставляет `ref` или `computed`, он не будет развернут в `<template>` компонента.** :br
Это связано с тем, что Vue работает со ссылками, которые не относятся к верхнему уровню шаблона. Подробнее об этом можно прочитать [в документации Vue](https://ru.vuejs.org/guide/essentials/reactivity-fundamentals.html#caveat-when-unwrapping-in-templates).
::

## Typing Plugins
## Типизация плагинов

If you return your helpers from the plugin, they will be typed automatically; you'll find them typed for the return of `useNuxtApp()` and within your templates.
Если вы вернете свои хэлперы из плагина, они будут автоматически типизированы; вы найдете их типизацию для возврата `useNuxtApp()` и в ваших шаблонах.

::note
If you need to use a provided helper _within_ another plugin, you can call [`useNuxtApp()`](/docs/api/composables/use-nuxt-app) to get the typed version. But in general, this should be avoided unless you are certain of the plugins' order.
Если вам нужно использовать предоставленный хэлпер _в_ другом плагине, вы можете вызвать [`useNuxtApp()`](/docs/api/composables/use-nuxt-app), чтобы получить типизированную версию. Но в целом, этого следует избегать, если вы не уверены в порядке расположения плагинов.
::

For advanced use-cases, you can declare the type of injected properties like this:
Для более сложных случаев использования можно объявить тип инжектируемых свойств следующим образом:

```ts [index.d.ts]
declare module '#app' {
Expand All @@ -237,14 +237,14 @@ export {}
```

::note
If you are using WebStorm, you may need to augment `@vue/runtime-core` until [this issue](https://youtrack.jetbrains.com/issue/WEB-59818/VUE-TypeScript-WS-PS-does-not-correctly-display-type-of-globally-injected-properties) is resolved.
Если вы используете WebStorm, вам может потребоваться дополнить `@vue/runtime-core` до тех пор, пока [эта проблема](https://youtrack.jetbrains.com/issue/WEB-59818/VUE-TypeScript-WS-PS-does-not-correctly-display-type-of-globally-injected-properties) не будет решена.
::

## Vue Plugins
## Плагины Vue

If you want to use Vue plugins, like [vue-gtag](https://github.com/MatteoGabriele/vue-gtag) to add Google Analytics tags, you can use a Nuxt plugin to do so.
Если вы хотите использовать плагины Vue, например [vue-gtag](https://github.com/MatteoGabriele/vue-gtag) для добавления тегов Google Analytics, вы можете использовать для этого плагин Nuxt.

First, install the Vue plugin dependency:
Сначала установите зависимость плагина Vue:

::code-group
```bash [yarn]
Expand All @@ -261,7 +261,7 @@ bun add -D vue-gtag-next
```
::

Then create a plugin file:
Затем создайте файл плагина:

```ts [plugins/vue-gtag.client.ts]
import VueGtag, { trackRouter } from 'vue-gtag-next'
Expand All @@ -276,9 +276,9 @@ export default defineNuxtPlugin((nuxtApp) => {
})
```

## Vue Directives
## Директивы Vue

Similarly, you can register a custom Vue directive in a plugin.
Аналогичным образом вы можете зарегистрировать пользовательскую директиву Vue в плагине.

```ts twoslash [plugins/my-directive.ts]
export default defineNuxtPlugin((nuxtApp) => {
Expand All @@ -287,15 +287,15 @@ export default defineNuxtPlugin((nuxtApp) => {
el.focus()
},
getSSRProps (binding, vnode) {
// you can provide SSR-specific props here
// Здесь вы можете предоставить входные параметры, специфичные для SSR
return {}
}
})
})
```

::warning
If you register a Vue directive, you _must_ register it on both client and server side unless you are only using it when rendering one side. If the directive only makes sense from a client side, you can always move it to `~/plugins/my-directive.client.ts` and provide a 'stub' directive for the server in `~/plugins/my-directive.server.ts`.
Если вы регистрируете директиву Vue, вы _должны_ зарегистрировать ее как на стороне клиента, так и на стороне сервера, если вы не используете ее только при рендеринге одной стороны. Если директива имеет смысл только на стороне клиента, вы всегда можете переместить ее в `~/plugins/my-directive.client.ts` и предоставить директиву 'заглушку' для сервера в `~/plugins/my-directive.server.ts`.
::

:read-more{icon="i-simple-icons-vuedotjs" title="Custom Directives on Vue Docs" to="https://ru.vuejs.org/guide/reusability/custom-directives.html" target="_blank"}

0 comments on commit 9ed4955

Please sign in to comment.