From f20bbfcc5a54deaa23cf432e9b5eba1f1cfcd0f6 Mon Sep 17 00:00:00 2001 From: Roman Akhmadullin <37641303+akhmadullin@users.noreply.github.com> Date: Mon, 25 Oct 2021 17:13:04 +1000 Subject: (ru) Translate the rest of Web/JavaScript/Guide/Modules page (#2730) Co-authored-by: Sasha Sushko --- files/ru/web/javascript/guide/modules/index.html | 305 +++++++++++++---------- 1 file changed, 180 insertions(+), 125 deletions(-) (limited to 'files') diff --git a/files/ru/web/javascript/guide/modules/index.html b/files/ru/web/javascript/guide/modules/index.html index 45148d3202..8bf2b4af9c 100644 --- a/files/ru/web/javascript/guide/modules/index.html +++ b/files/ru/web/javascript/guide/modules/index.html @@ -27,19 +27,21 @@ translation_of: Web/JavaScript/Guide/Modules

{{Compat("javascript.statements.export")}}

-

Introducing an example

+

Пример использования модулей

-

To demonstrate usage of modules, we've created a simple set of examples that you can find on GitHub. These examples demonstrate a simple set of modules that create a <canvas> element on a webpage, and then draw (and report information about) different shapes on the canvas.

+

Для того, чтобы продемонстрировать использование модулей, мы создали простой набор примеров, который вы можете найти на GitHub. + В этих примерах мы создаём элемент <canvas> + на веб-странице и затем рисуем различные фигуры на нём (и выводим информацию об этом).

-

These are fairly trivial, but have been kept deliberately simple to demonstrate modules clearly.

+

Примеры довольно тривиальны, но они намеренно сделаны простыми для ясной демонстрации модулей.

-

Note: If you want to download the examples and run them locally, you'll need to run them through a local web server.

+

Примечание: Если вы хотите скачать примеры и запустить их локально, вам нужно будет запустить их через локальный веб-сервер.

-

Basic example structure

+

Базовая структура примера

-

In our first example (see basic-modules) we have a file structure as follows:

+

В первом примере (см. директорию basic-modules) у нас следующая структура файлов:

index.html
 main.js
@@ -48,58 +50,61 @@ modules/
     square.js
-

Note: All of the examples in this guide have basically the same structure; the above should start getting pretty familiar.

+

Примечание: Все примеры в этом руководстве в основном имеют одинаковую структуру.

-

The modules directory's two modules are described below:

+

Давайте разберём два модуля из директории modules:

-

Aside — .mjs versus .js

+

Взгляд со стороны — .mjs против .js

-

Throughout this article, we've used .js extensions for our module files, but in other resources you may see the .mjs extension used instead. V8's documentation recommends this, for example. The reasons given are:

+

В этой статье мы используем расширение .js для файлов наших модулей, но в других источниках вы можете встретить расширение .mjs. Например, в документации движка V8 используется .mjs. Причины следующие:

-

However, we decided to keep to using .js, at least for the moment. To get modules to work correctly in a browser, you need to make sure that your server is serving them with a Content-Type header that contains a JavaScript MIME type such as text/javascript. If you don't, you'll get a strict MIME type checking error along the lines of "The server responded with a non-JavaScript MIME type" and the browser won't run your JavaScript. Most servers already set the correct type for .js files, but not yet for .mjs files. Servers that already serve .mjs files correctly include GitHub Pages and http-server for Node.js.

+

Тем не менее, мы решили продолжать использовать .js, по крайней мере на данным момент. Чтобы модули корректно работали в браузере, вам нужно убедиться, что ваш сервер отдаёт их с заголовком Content-Type, который содержит JavaScript MIME type такой как text/javascript. В противном случае вы получете ошибку проверки MIME type — "The server responded with a non-JavaScript MIME type", и браузер не сможет запустить ваш JavaScript. Большинство серверов уже имеют правильный тип для .js-файлов, но ещё не имеют нужного MIME type для .mjs-файлов. Серверы, которые уже отдают .mjs файлы корректно, включают в себя GitHub Pagesи http-сервер для Node.js.

-

This is OK if you are using such an environment already, or if you aren't but you know what you are doing and have access (i.e. you can configure your server to set the correct Content-Type for .mjs files). It could however cause confusion if you don't control the server you are serving files from, or are publishing files for public use, as we are here.

+

Это нормально, если вы уже используете такую среду или ещё нет, но знаете, что делать, и имеете нужные доступы (то есть вы можете настроить свой сервер, чтобы он устанавливал корректный Content-Type-заголовок для .mjs-файлов). + Однако это может вызвать путаницу, если вы не контролируете сервер, с которого отдаются файлы, или публикуете файлы для общего пользования, как мы здесь.

-

For learning and portability purposes, we decided to keep to .js.

+

В целях обучения и переносимости на разные платформы мы решили остановится на .js.

-

If you really value the clarity of using .mjs for modules versus using .js for "normal" JavaScript files, but don't want to run into the problem described above, you could always use .mjs during development and convert them to .js during your build step.

+

Если вы действительно видите ценность и ясность использования .mjs для модулей по сравнению с использованием .js для обычных JavaScript-файлов, + но не хотите столкнуться с проблемой описанной выше, вы должны всегда использовать .mjs во время разработки + и конвертировать их в .js во время сборки.

-

It is also worth noting that:

+

Также стоит отметить, что:

-

Exporting module features

+

Экспорт функционала модуля

-

The first thing you do to get access to module features is export them. This is done using the {{JSxRef("Statements/export", "export")}} statement.

+

Первое, что нужно сделать, чтобы получить доступ к функционалу модуля, — экспортировать его. Это делается с помощью инструкции {{JSxRef("Statements/export", "export")}}.

-

The easiest way to use it is to place it in front of any items you want exported out of the module, for example:

+

Самый простой способ использовать экспорт — поместить конструкцию export перед любыми элементами, которые вы хотите экспортировать из модуля, например:

export const name = 'square';
 
@@ -115,37 +120,40 @@ export function draw(ctx, length, x, y, color) {
   };
 }
-

You can export functions, var, let, const, and — as we'll see later — classes. They need to be top-level items; you can't use export inside a function, for example.

+

Вы можете экспортировать var-, let-, const-переменные, и — как мы увидим позже — классы. + Они должны быть в верхней области видимости, вы не можете использовать export внутри функции, например.

-

A more convenient way of exporting all the items you want to export is to use a single export statement at the end of your module file, followed by a comma-separated list of the features you want to export wrapped in curly braces. For example:

+

Более удобный способ экспорта всех элементов, которые вы хотите экспортировать,— использовать одну конструкцию export в конце файла модуля, где указать переменные, функции, классы, который вы хотите экспортировать, через запятую в фигурных скобках. Например:

export { name, draw, reportArea, reportPerimeter };
-

Importing features into your script

+

Импорт функционала в ваш скрипт

-

Once you've exported some features out of your module, you need to import them into your script to be able to use them. The simplest way to do this is as follows:

+

После того, как вы экспортировали некоторые функции из своего модуля, вам необходимо импортировать их в свой скрипт, чтобы иметь возможность использовать их. Самый простой способ сделать это:

import { name, draw, reportArea, reportPerimeter } from './modules/square.js';
-

You use the {{JSxRef("Statements/import", "import")}} statement, followed by a comma-separated list of the features you want to import wrapped in curly braces, followed by the keyword from, followed by the path to the module file — a path relative to the site root, which for our basic-modules example would be /js-examples/modules/basic-modules.

+

Используйте конструкцию {{JSxRef("Statements/import", "import")}}, за которой следует разделенный запятыми список функций, которые вы хотите импортировать, заключённый в фигурные скобки, за которым следует ключевое слово from, за которым следует путь к файлу модуля — путь относительно корня сайта, который для нашего примера basic-modules будет равен /js-examples/modules/basic-modules.

-

However, we've written the path a bit differently — we are using the dot (.) syntax to mean "the current location", followed by the path beyond that to the file we are trying to find. This is much better than writing out the entire relative path each time, as it is shorter, and it makes the URL portable — the example will still work if you move it to a different location in the site hierarchy.

+

Однако, мы написали путь немного иначе — мы используем (.) синтаксис, означающий "текущую директорию", за которым следует путь к файлу, который мы пытаемся найти. + Это намного лучше, чем каждый раз записывать весь относительный путь, поскольку он короче и делает URL-адрес переносимым - пример все равно будет работать, если вы переместите его в другое место в иерархии сайта.

-

So for example:

+

Так например:

/js-examples/modules/basic-modules/modules/square.js
-

becomes

+

становится

./modules/square.js
-

You can see such lines in action in main.js.

+

Вы можете найти подобные строки кода в файле main.js.

-

Note: In some module systems, you can omit the file extension and the leading /, ./, or ../ (e.g. 'modules/square'). This doesn't work in native JavaScript modules.

+

Примечание: В некоторых модульных системах вы можете опустить расширение файла и начальные /, ./, or ../ (например 'modules/square'). Это не работает в нативных JavaScript-модулях.

-

Once you've imported the features into your script, you can use them just like they were defined inside the same file. The following is found in main.js, below the import lines:

+

После того, как вы импортировали функции в свой скрипт, вы можете использовать их так же, как если бы они были определены в этом же файле. + Следующий пример можно найти в main.js, сразу за строками импорта:

let myCanvas = create('myCanvas', document.body, 480, 320);
 let reportList = createReportList(myCanvas.id);
@@ -156,110 +164,127 @@ reportPerimeter(square1.length, reportList);
 
-

Note: Although imported features are available in the file, they are read only views of the feature that was exported. You cannot change the variable that was imported, but you can still modify properties similar to const. Additionally, these features are imported as live bindings, meaning that they can change in value even if you cannot modify the binding unlike const.

+

Примечание:  + Хотя импортированные функции доступны в файле, они доступны только для чтения. + Вы не можете изменить импортированную переменную, но вы всё равно можете изменять свойства у const-переменных. + Кроме того, переменные импортируется как "live bindings" - + это означает, что они могут меняться по значению, даже если вы не можете изменить привязку, в отличие от const.

-

Applying the module to your HTML

+

Добавление модуля на HTML-страницу

-

Now we just need to apply the main.js module to our HTML page. This is very similar to how we apply a regular script to a page, with a few notable differences.

+

Далее нам необходимо подключить модуль main.js на нашу HTML-страницу. Это очень похоже на то, как мы подключаем обычный скрипт на страницу, с некоторыми заметными отличиями.

-

First of all, you need to include type="module" in the <script> element, to declare this script as a module. To import the main.js script, we use this:

+

Прежде всего, вам нужно добавить type="module" в <script>-элемент, чтобы объявить, что скрипт является модулем. Чтобы подключить модуль main.js, нужно написать следующее:

<script type="module" src="main.js"></script>
-

You can also embed the module's script directly into the HTML file by placing the JavaScript code within the body of the <script> element:

+

Вы также можете встроить скрипт модуля непосредственно в HTML-файл, поместив JavaScript-код внутрь <script>-элемента:

<script type="module">
-  /* JavaScript module code here */
+  /* код JavaScript модуля */
 </script>
-

The script into which you import the module features basically acts as the top-level module. If you omit it, Firefox for example gives you an error of "SyntaxError: import declarations may only appear at top level of a module".

+

Скрипт, в который вы импортируете функционал модуля, в основном действует как модуль верхнего уровня. + Если вы упустите это, то Firefox, например, выдаст ошибку "SyntaxError: import declarations may only appear at top level of a module".

-

You can only use import and export statements inside modules, not regular scripts.

+

Вы можете использовать import и export инструкции только внутри модулей, внутри обычных скриптов они работать не будут.

-

Other differences between modules and standard scripts

+

Другие отличия модулей от обычных скриптов

-

Default exports versus named exports

+

Экпорт по умолчанию против именнованого экспорта

-

The functionality we've exported so far has been comprised of named exports — each item (be it a function, const, etc.) has been referred to by its name upon export, and that name has been used to refer to it on import as well.

+

Экспорты функций и переменных, которые мы использовали в примерах выше являются именованными экспортами — каждый элемент (будь то функция или const-переменная, например) упоминается по имени при экспорте, и это имя также используется для ссылки на него при импорте.

-

There is also a type of export called the default export — this is designed to make it easy to have a default function provided by a module, and also helps JavaScript modules to interoperate with existing CommonJS and AMD module systems (as explained nicely in ES6 In Depth: Modules by Jason Orendorff; search for "Default exports").

+

Существует также тип экспорта, который называется экспорт по умолчанию — + это сделано для того, чтобы упростить использование экпортируемого функционала сторонним модулем, + а также помогает модулям JavaScript взаимодействовать с существующими модульными системами CommonJS и AMD (это хорошо объясняется в статье ES6 в деталях: Модули от Джейсон Орендорфа — ищите по ключевому слову «Default exports»).

-

Let's look at an example as we explain how it works. In our basic-modules square.js you can find a function called randomSquare() that creates a square with a random color, size, and position. We want to export this as our default, so at the bottom of the file we write this:

+

Давайте посмотрим на пример, и мы объясним, как это работает. + В модуле square.js из нашего примера вы можете найти функцию randomSquare(), которая создаёт квардрат случайного цвета и размера со случайными координатами. Мы хотим экпортировать эту функции по умолчанию, поэтому в конце файла пишем следующее:

export default randomSquare;
-

Note the lack of curly braces.

+

Обратите внимание на отсутствие фигурных скобок.

-

We could instead prepend export default onto the function and define it as an anonymous function, like this:

+

Кстати, можно было бы определить функцию как анонимную и добавить к ней export default:

export default function(ctx) {
   ...
 }
-

Over in our main.js file, we import the default function using this line:

+

В нашем файле main.js мы импортируем функцию по умолчанию, используя эту строку:

import randomSquare from './modules/square.js';
-

Again, note the lack of curly braces. This is because there is only one default export allowed per module, and we know that randomSquare is it. The above line is basically shorthand for:

+

Снова обратите внимание на отсутствие фигурных скобок. + Такой синтакис допустим, поскольку для каждого модуля разрешен только один экспорт по умолчанию, и мы знаем, что это randomSquare. + Вышеупомянутая строка является сокращением для:

import {default as randomSquare} from './modules/square.js';
-

Note: The as syntax for renaming exported items is explained below in the Renaming imports and exports section.

+

Примечание: «as» синтаксис для переименования экспортируемых элементов поясняется ниже в разделе Переименование импорта и экмпорта.

-

Avoiding naming conflicts

+

Как избежать конфликтов имён

-

So far, our canvas shape drawing modules seem to be working OK. But what happens if we try to add a module that deals with drawing another shape, like a circle or triangle? These shapes would probably have associated functions like draw(), reportArea(), etc. too; if we tried to import different functions of the same name into the same top-level module file, we'd end up with conflicts and errors.

+

Пока что наши модули для рисования фигур на холсте работают нормально. + Но что произойдёт, если мы попытаемся добавить модуль, который занимается рисованием другой фигуры, например круга или треугольника? + С этими фигурами, вероятно, тоже будут связаны такие функции, как draw(), reportArea() и т.д.; + если бы мы попытались импортировать разные функции с одним и тем же именем в один и тот же файл модуля верхнего уровня, мы бы столкнулись с конфликтами и ошибками.

-

Fortunately there are a number of ways to get around this. We'll look at these in the following sections.

+

К счастью, есть несколько способов обойти это. Мы рассмотрим их в следующих разделах.

-

Renaming imports and exports

+

Переименование импорта и экспорта

-

Inside your import and export statement's curly braces, you can use the keyword as along with a new feature name, to change the identifying name you will use for a feature inside the top-level module.

+

Внутри фигурных скобок инструкций import и export вы можете использовать ключевое слово as вместе с новым именем функционала, чтобы задать ему новое имя, которое вы будете использовать для него внутри модуля верхнего уровня.

-

So for example, both of the following would do the same job, albeit in a slightly different way:

+

Так, например, оба следующих элемента будут выполнять одну и ту же работу, хотя и немного по-разному:

-
// inside module.js
+
// внутри module.js
 export {
   function1 as newFunctionName,
   function2 as anotherNewFunctionName
 };
 
-// inside main.js
+// внутри main.js
 import { newFunctionName, anotherNewFunctionName } from './modules/module.js';
-
// inside module.js
+
// внутри module.js
 export { function1, function2 };
 
-// inside main.js
+// внутри main.js
 import { function1 as newFunctionName,
          function2 as anotherNewFunctionName } from './modules/module.js';
-

Let's look at a real example. In our renaming directory you'll see the same module system as in the previous example, except that we've added circle.js and triangle.js modules to draw and report on circles and triangles.

+

Давайте посмотрим на реальный пример. В нашей renaming директории + вы увидите ту же модульную систему, что и в предыдущем примере, + за исключением того, что мы добавили модули circle.js и triangle.js для рисования кругов и треугольников и создания отчетов по ним.

-

Inside each of these modules, we've got features with the same names being exported, and therefore each has the same export statement at the bottom:

+

Внутри каждого из этих модулей у нас есть функции с одинаковыми именами, которые экспортируются, и поэтому у каждого из них есть один и тот же оператор export внизу файла:

export { name, draw, reportArea, reportPerimeter };
-

When importing these into main.js, if we tried to use

+

Если бы в main.js при их импорте мы попытались использовать

import { name, draw, reportArea, reportPerimeter } from './modules/square.js';
 import { name, draw, reportArea, reportPerimeter } from './modules/circle.js';
 import { name, draw, reportArea, reportPerimeter } from './modules/triangle.js';
-

The browser would throw an error such as "SyntaxError: redeclaration of import name" (Firefox).

+

то браузер выдал бы ошибку — "SyntaxError: redeclaration of import name" (Firefox).

-

Instead we need to rename the imports so that they are unique:

+

Вместо этого нам нужно переименовать импорт, чтобы он был уникальным:

import { name as squareName,
          draw as drawSquare,
@@ -276,36 +301,43 @@ import { name as triangleName,
         reportArea as reportTriangleArea,
         reportPerimeter as reportTrianglePerimeter } from './modules/triangle.js';
-

Note that you could solve the problem in the module files instead, e.g.

+

Обратите внимание, что вместо этого вы можете решить проблему в файлах модуля, например.

-
// in square.js
+
// внутри square.js
 export { name as squareName,
          draw as drawSquare,
          reportArea as reportSquareArea,
          reportPerimeter as reportSquarePerimeter };
-
// in main.js
+
// внутри main.js
 import { squareName, drawSquare, reportSquareArea, reportSquarePerimeter } from './modules/square.js';
-

And it would work just the same. What style you use is up to you, however it arguably makes more sense to leave your module code alone, and make the changes in the imports. This especially makes sense when you are importing from third party modules that you don't have any control over.

+

И это сработало бы точно так же. + Какой способ вы будете использовать, зависит от вас, однако, возможно, имеет смысл оставить код модуля в покое и внести изменения в импорт. + Это особенно важно, когда вы импортируете из сторонних модулей, над которыми у вас нет никакого контроля.

-

Creating a module object

+

Создание объекта модуля

-

The above method works OK, but it's a little messy and longwinded. An even better solution is to import each module's features inside a module object. The following syntax form does that:

+

Вышеупомянутый способ работает нормально, но он немного запутан и многословен. + Существует решение получше — импортировать функции каждого модуля внутри объекта модуля. + Для этого используется следующая синтаксическая форма:

import * as Module from './modules/module.js';
-

This grabs all the exports available inside module.js, and makes them available as members of an object Module, effectively giving it its own namespace. So for example:

+

Эта конструкция берёт все экспорты, доступные внутри module.js и делает их доступными в качестве свойств объекта Module, фактически давая ему собственное пространство имен. Так например:

Module.function1()
 Module.function2()
-etc.
+
+и т.д. -

Again, let's look at a real example. If you go to our module-objects directory, you'll see the same example again, but rewritten to take advantage of this new syntax. In the modules, the exports are all in the following simple form:

+

Опять же, давайте посмотрим на реальный пример. Если вы посмотрите на нашу директорию module-objects, + вы снова увидите тот же самый пример, но переписанный с учётом преимуществ этого нового синтаксиса. + В модулях все экспорты представлены в следующей простой форме:

export { name, draw, reportArea, reportPerimeter };
-

The imports on the other hand look like this:

+

С другой стороны, импорт выглядит так:

import * as Canvas from './modules/canvas.js';
 
@@ -313,19 +345,20 @@ import * as Square from './modules/square.js';
 import * as Circle from './modules/circle.js';
 import * as Triangle from './modules/triangle.js';
-

In each case, you can now access the module's imports underneath the specified object name, for example:

+

В каждом случае теперь вы можете получить доступ к импорту модуля под указанным свойством объекта, например:

let square1 = Square.draw(myCanvas.ctx, 50, 50, 100, 'blue');
 Square.reportArea(square1.length, reportList);
 Square.reportPerimeter(square1.length, reportList);
-

So you can now write the code just the same as before (as long as you include the object names where needed), and the imports are much neater.

+

Таким образом, теперь вы можете написать код точно так же, как и раньше (при условии, что вы включаете имена объектов там, где это необходимо), и импорт будет намного более аккуратным.

-

Modules and classes

+

Модули и классы

-

As we hinted at earlier, you can also export and import classes; this is another option for avoiding conflicts in your code, and is especially useful if you've already got your module code written in an object-oriented style.

+

Как мы намекали ранее, вы также можете экспортировать и импортировать классы — это ещё один способ избежать конфликтов в вашем коде, и он особенно полезен, если у вас уже есть код модуля, написанный в объектно-ориентированном стиле.

-

You can see an example of our shape drawing module rewritten with ES classes in our classes directory. As an example, the square.js file now contains all its functionality in a single class:

+

Вы можете увидеть пример нашего модуля для рисования фигур, переписанного с помощью классов ES в нашей classes директории. + В качестве примера, файд square.js теперь содержит всю свою функциональность в одном классе:

class Square {
   constructor(ctx, listId, length, x, y, color) {
@@ -339,29 +372,35 @@ Square.reportPerimeter(square1.length, reportList);
... }
-

which we then export:

+

который мы затем экспортируем:

export { Square };
-

Over in main.js, we import it like this:

+

Далее в main.js, мы импортируем его так:

import { Square } from './modules/square.js';
-

And then use the class to draw our square:

+

А затем используем импортированный класс, чтобы нарисовать наш квадрат:

let square1 = new Square(myCanvas.ctx, myCanvas.listId, 50, 50, 100, 'blue');
 square1.draw();
 square1.reportArea();
 square1.reportPerimeter();
-

Aggregating modules

+

Агрегирующие модули

-

There will be times where you'll want to aggregate modules together. You might have multiple levels of dependencies, where you want to simplify things, combining several submodules into one parent module. This is possible using export syntax of the following forms in the parent module:

+

Возможны случаи, когда вы захотите объединить модули вместе. + У вас может быть несколько уровней зависимостей, где вы хотите упростить вещи, объединив несколько подмодулей в один родительский модуль. + Это возможно с использованием следующего синтаксиса экспорта в родительском модуле:

export * from 'x.js'
 export { name } from 'x.js'
-

For an example, see our module-aggregation directory. In this example (based on our earlier classes example) we've got an extra module called shapes.js, which aggregates all the functionality from circle.js, square.js, and triangle.js together. We've also moved our submodules inside a subdirectory inside the modules directory called shapes. So the module structure in this example is:

+

Для примера посмотрите на нашу директорию module-aggregation. + В этом примере (на основе нашего предыдущего примера с классами) у нас есть дополнительный модуль с именем shapes.js, + который собирает функциональность circle.js, square.js и triangle.js вместе. + Мы также переместили наши подмодули в дочернюю директорию внутри директории modules под названием shape. + Итак, структура модуля в этом примере:

modules/
   canvas.js
@@ -371,52 +410,59 @@ export { name } from 'x.js'
square.js triangle.js
-

In each of the submodules, the export is of the same form, e.g.

+

В каждом из подмодулей экспорт имеет одинаковую форму, например:

export { Square };
-

Next up comes the aggregation part. Inside shapes.js, we include the following lines:

+

Далее идет агрегирование. + Внутри shapes.js, мы добавляем следующие строки:

export { Square } from './shapes/square.js';
 export { Triangle } from './shapes/triangle.js';
 export { Circle } from './shapes/circle.js';
-

These grab the exports from the individual submodules and effectively make them available from the shapes.js module.

+

Они берут экспорт из отдельных подмодулей и фактически делают их доступными из модуля shape.js.

-

Note: The exports referenced in shapes.js basically get redirected through the file and don't really exist there, so you won't be able to write any useful related code inside the same file.

+

Примечание: Экспорты, указанные в shape.js, по сути перенаправляются через файл и на самом деле там не существуют, поэтому вы не сможете написать какой-либо полезный связанный код внутри того же файла.

-

So now in the main.js file, we can get access to all three module classes by replacing

+

Итак, теперь в файле main.js мы можем получить доступ ко всем трём классам модулей, заменив:

import { Square } from './modules/square.js';
 import { Circle } from './modules/circle.js';
 import { Triangle } from './modules/triangle.js';
-

with the following single line:

+

на единственную строку кода:

import { Square, Circle, Triangle } from './modules/shapes.js';
-

Dynamic module loading

+

Динамическая загрузка модулей

-

The newest part of the JavaScript modules functionality to be available in browsers is dynamic module loading. This allows you to dynamically load modules only when they are needed, rather than having to load everything up front. This has some obvious performance advantages; let's read on and see how it works.

+

Самая свежая возмжность JavaScript-модулей доступная в браузерах,— это динамическая загрузка модулей. + Это позволяет вам динамически загружать модули только тогда, когда они необходимы, вместо того, чтобы загружать всё заранее. + Это даёт очевидные преимущества в производительности — давайте продолжим читать и посмотрим, как это работает.

-

This new functionality allows you to call {{JSxRef("Statements/import", "import()", "#Dynamic_Imports")}} as a function, passing it the path to the module as a parameter. It returns a {{JSxRef("Promise")}}, which fulfills with a module object (see Creating a module object) giving you access to that object's exports, e.g.

+

Поддержка динамической загрузки модулей позволяет вызывать {{JSxRef("Statements/import", "import()", "#Dynamic_Imports")}} в качестве функции, передав ей аргументом путь к модулю. + Данный вызов возвращает {{JSxRef("Promise")}}, который резолвится объектом модуля (см. Создание объекта модуля), предоставляя вам доступ к экспорту указанного модуля, например:

import('./modules/myModule.js')
   .then((module) => {
-    // Do something with the module.
+    // делаем что-то с функционалом из импортированного модуля
   });
-

Let's look at an example. In the dynamic-module-imports directory we've got another example based on our classes example. This time however we are not drawing anything on the canvas when the example loads. Instead, we include three buttons — "Circle", "Square", and "Triangle" — that, when pressed, dynamically load the required module and then use it to draw the associated shape.

+

Давайте посмотрим на пример. + В директории dynamic-module-imports у нас есть ещё один пример, основанный на примере наших классов. + Однако на этот раз мы ничего не рисуем на холсте при загрузке страницы. + Вместо этого мы добавляем на страницу три кнопки — «Circle», «Square» и «Triangle», которые при нажатии динамически загружают требуемый модуль, а затем используют его для рисования указанной фигуры.

-

In this example we've only made changes to our index.html and main.js files — the module exports remain the same as before.

+

В этом примере мы внесли изменения только в наши index.html и main.js — экспорт модуля остается таким же, как и раньше.

-

Over in main.js we've grabbed a reference to each button using a Document.querySelector() call, for example:

+

Далее в main.js мы взяли ссылку на каждую кнопку, используя вызов document.querySelector():

let squareBtn = document.querySelector('.square');
-

We then attach an event listener to each button so that when pressed, the relevant module is dynamically loaded and used to draw the shape:

+

Затем мы добавляем обработчик событий на каждую кнопку, чтобы при нажатии соответствующий модуль динамически загружался и использовался для рисования фигуры:

squareBtn.addEventListener('click', () => {
   import('./modules/square.js').then((Module) => {
@@ -427,25 +473,34 @@ import { Triangle } from './modules/triangle.js';
}) });
-

Note that, because the promise fulfillment returns a module object, the class is then made a subfeature of the object, hence we now need to access the constructor with Module. prepended to it, e.g. Module.Square( ... ).

+

Обратите внимание: поскольку выполнение Promise возвращает объект модуля, класс затем становится подкомпонентом объекта, поэтому теперь для получения доступа к конструктору нам нужно добавить к нему Module., например Module.Square(...).

-

Troubleshooting

+

Устранение проблем

-

Here are a few tips that may help you if you are having trouble getting your modules to work. Feel free to add to the list if you discover more!

+

Вот несколько советов, которые могут помочь вам, если вам не удаётся заставить ваши модули работать. + Не стесняйтесь дополнять список, если найдете что-то ещё!

-

See also

+

Смотрите также

{{Previous("Web/JavaScript/Guide/Meta_programming")}}

-- cgit v1.2.3-54-g00ecf