Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(docs): Локализация docs/guide/going-further/internals.md #231

Merged
merged 8 commits into from
Jun 30, 2024
63 changes: 30 additions & 33 deletions docs/2.guide/3.going-further/1.internals.md
Original file line number Diff line number Diff line change
@@ -1,54 +1,51 @@
---
title: "How Nuxt Works?"
description: "Nuxt is a minimal but highly customizable framework to build web applications."
title: "Как работает Nuxt?"
description: "Nuxt - это минималистичный, но легко настраиваемый фреймворк для создания веб-приложений."
---

This guide helps you better understand Nuxt internals to develop new solutions and module integrations on top of Nuxt.
Это руководство поможет вам лучше понять внутреннее устройство Nuxt для разработки новых решений и интеграции модулей поверх Nuxt.

## The Nuxt Interface
## Интерфейс Nuxt

When you start Nuxt in development mode with [`nuxi dev`](/docs/api/commands/dev) or building a production application with [`nuxi build`](/docs/api/commands/build),
a common context will be created, referred to as `nuxt` internally. It holds normalized options merged with `nuxt.config` file,
some internal state, and a powerful [hooking system](/docs/api/advanced/hooks) powered by [unjs/hookable](https://github.com/unjs/hookable)
allowing different components to communicate with each other. You can think of it as **Builder Core**.
Когда вы запускаете Nuxt в режиме разработки с помощью [`nuxi dev`](/docs/api/commands/dev) или создаете продакшен приложение с помощью [`nuxi build`](/docs/api/commands/build), будет создан общий контекст, который внутренне называется `nuxt`. Он содержит нормализованные опции, объединенные с файлом `nuxt.config`, некоторое внутреннее состояние и мощную [систему хуков](/docs/api/advanced/hooks) на основе [unjs/hookable](https://github.com/unjs/hookable), позволяющих различным компонентам взаимодействовать друг с другом. Можно считать, что это **Ядро Сборщика**.

This context is globally available to be used with [Nuxt Kit](/docs/guide/going-further/kit) composables.
Therefore only one instance of Nuxt is allowed to run per process.
Этот контекст глобально доступен для использования с композаблами [Nuxt Kit](/docs/guide/going-further/kit).
Поэтому в каждом процессе может быть запущен только один инстанс Nuxt.

To extend the Nuxt interface and hook into different stages of the build process, we can use [Nuxt Modules](/docs/guide/going-further/modules).
Чтобы расширить интерфейс Nuxt и подключиться к различным этапам процесса сборки, мы можем использовать [Nuxt-модули](/docs/guide/going-further/modules).

For more details, check out [the source code](https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/core/nuxt.ts).
Для получения более подробной информации ознакомьтесь с [исходным кодом](https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/core/nuxt.ts).

## The NuxtApp Interface
## Интерфейс NuxtApp

When rendering a page in the browser or on the server, a shared context will be created, referred to as `nuxtApp`.
This context keeps vue instance, runtime hooks, and internal states like ssrContext and payload for hydration.
You can think of it as **Runtime Core**.
При рендере страницы в браузере или на сервере будет создан общий контекст, называемый `nuxtApp`.
В этом контексте хранятся инстанс vue, runtime хуки, а также внутренние состояния, такие как ssrContext и payload для гидратации.
Можно считать, что это **Runtime ядро**.

This context can be accessed using [`useNuxtApp()`](/docs/api/composables/use-nuxt-app) composable within Nuxt plugins and `<script setup>` and vue composables.
Global usage is possible for the browser but not on the server, to avoid sharing context between users.
Доступ к этому контексту можно получить с помощью композабла [`useNuxtApp()`](/docs/api/composables/use-nuxt-app) в Nuxt-плагинах, а также с помощью `<script setup>` и композаблов vue.
Глобальное использование возможно в браузере, но не на сервере, чтобы избежать совместного использования контекста между пользователями.

Since [`useNuxtApp`](/docs/api/composables/use-nuxt-app) throws an exception if context is currently unavailable, if your composable does not always require `nuxtApp`, you can use [`tryUseNuxtApp`](/docs/api/composables/use-nuxt-app#tryusenuxtapp) instead, which will return `null` instead of throwing an exception.
Поскольку [`useNuxtApp`](/docs/api/composables/use-nuxt-app) выбрасывает исключение, если контекст в данный момент недоступен, если ваш композабл не всегда требует `nuxtApp`, вы можете использовать вместо него [`tryUseNuxtApp`](/docs/api/composables/use-nuxt-app#tryusenuxtapp), оторый вернет `null` вместо того, чтобы выбросить исключение.

To extend the `nuxtApp` interface and hook into different stages or access contexts, we can use [Nuxt Plugins](/docs/guide/directory-structure/plugins).
Для расширения интерфейса `nuxtApp` и подключения к различным этапам или контекстам доступа можно использовать [Nuxt-плагины](/docs/guide/directory-structure/plugins).

Check [Nuxt App](/docs/api/composables/use-nuxt-app) for more information about this interface.
Дополнительную информацию об этом интерфейсе можно найти в [Nuxt App](/docs/api/composables/use-nuxt-app).

`nuxtApp` has the following properties:
`nuxtApp` имеет следующие свойства:

```js
const nuxtApp = {
vueApp, // the global Vue application: https://ru.vuejs.org/api/application.html#application-api
vueApp, // глобальное приложение Vue: https://ru.vuejs.org/api/application.html#application-api

versions, // an object containing Nuxt and Vue versions
versions, // объект, содержащий версии Nuxt и Vue

// These let you call and add runtime NuxtApp hooks
// Они позволяют вызывать и добавлять runtime хуки NuxtApp
// https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/app/nuxt.ts#L18
hooks,
hook,
callHook,

// Only accessible on server-side
// Доступно только на сервере
ssrContext: {
url,
req,
Expand All @@ -57,7 +54,7 @@ const nuxtApp = {
noSSR,
},

// This will be stringified and passed from server to client
// Это будет преобразовано в строку и передано от сервера к клиенту
payload: {
serverRendered: true,
data: {},
Expand All @@ -68,14 +65,14 @@ const nuxtApp = {
}
```

For more details, check out [the source code](https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/app/nuxt.ts).
Более подробную информацию можно найти в [исходном коде](https://github.com/nuxt/nuxt/blob/main/packages/nuxt/src/app/nuxt.ts).

## Runtime Context vs. Build Context
## Runtime контекст против контекста сборки

Nuxt builds and bundles project using Node.js but also has a runtime side.
Nuxt собирает и компонует проект с помощью Node.js, но также имеет и runtime.

While both areas can be extended, that runtime context is isolated from build-time. Therefore, they are not supposed to share state, code, or context other than runtime configuration!
Хотя обе области могут быть расширены, runtime контекст изолирован от времени сборки. Поэтому они не должны иметь общего состояния, кода или контекста, отличного от runtime конфигурации!

`nuxt.config` and [Nuxt Modules](/docs/guide/going-further/modules) can be used to extend the build context, and [Nuxt Plugins](/docs/guide/directory-structure/plugins) can be used to extend runtime.
`nuxt.config` и [Nuxt-модули](/docs/guide/going-further/modules) могут использоваться для расширения контекста сборки, а [Nuxt-плагины](/docs/guide/directory-structure/plugins) - для расширения runtime.

When building an application for production, `nuxi build` will generate a standalone build in the `.output` directory, independent of `nuxt.config` and [Nuxt modules](/docs/guide/going-further/modules).
При сборке приложения для продакшена `nuxi build` будет генерировать отдельную сборку в директории `.output`, не зависящую от `nuxt.config` и [Nuxt-модулей](/docs/guide/going-further/modules).
Loading