Skip to content

Commit ecbc8a9

Browse files
authored
Dynamic imports (#234)
1 parent d26bab5 commit ecbc8a9

File tree

3 files changed

+37
-37
lines changed

3 files changed

+37
-37
lines changed
Lines changed: 30 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,61 +1,61 @@
1-
# Dynamic imports
1+
# Динамічні імпорти
22

3-
Export and import statements that we covered in previous chapters are called "static". The syntax is very simple and strict.
3+
Інструкції експорту і імпорту, які ми розглядали в попередньому розділі, називаються "статичними". Синтаксис у них дуже простий і строгий.
44

5-
First, we can't dynamically generate any parameters of `import`.
5+
По-перше, ми не можемо динамічно задавати ніякі з параметрів `import`.
66

7-
The module path must be a primitive string, can't be a function call. This won't work:
7+
Шлях до модуля має бути строковим примітивом і не може бути викликом функції. Ось так працювати не буде:
88

99
```js
10-
import ... from *!*getModuleName()*/!*; // Error, only from "string" is allowed
10+
import ... from *!*getModuleName()*/!*; // Помилка, має бути рядок
1111
```
1212

13-
Second, we can't import conditionally or at run-time:
13+
По-друге, ми не можемо робити імпорт залежно від умов або в процесі виконання:
1414

1515
```js
1616
if(...) {
17-
import ...; // Error, not allowed!
17+
import ...; // Помилка, заборонено
1818
}
1919

2020
{
21-
import ...; // Error, we can't put import in any block
21+
import ...; // Помилка, ми не можемо ставити імпорт у блок
2222
}
2323
```
2424

25-
That's because `import`/`export` aim to provide a backbone for the code structure. That's a good thing, as code structure can be analyzed, modules can be gathered and bundled into one file by special tools, unused exports can be removed ("tree-shaken"). That's possible only because the structure of imports/exports is simple and fixed.
25+
Усе це результат того, що мета директив `import`/`export` - задати кістяк структури коду. Завдяки ним вона може бути проаналізована, модулі можуть бути зібрані в один файл спеціальними інструментами, а невживані експорти видалені. Це можливо тільки завдяки тому, що все статично.
2626

27-
But how can we import a module dynamically, on-demand?
27+
Але як ми можемо імпортувати модуль динамічно, за запитом?
2828

29-
## The import() expression
29+
## Вираз import()
3030

31-
The `import(module)` expression loads the module and returns a promise that resolves into a module object that contains all its exports. It can be called from any place in the code.
31+
Вираз `import(module)` завантажує модуль і повертає проміс, результатом якого стає об’єкт модуля, що містить усі його експорти.
3232

33-
We can use it dynamically in any place of the code, for instance:
33+
Ми можемо використати його у будь-якому місці коду, наприклад, так:
3434

3535
```js
36-
let modulePath = prompt("Which module to load?");
36+
let modulePath = prompt("Який модуль завантажити?");
3737

3838
import(modulePath)
39-
.then(obj => <module object>)
40-
.catch(err => <loading error, e.g. if no such module>)
39+
.then(obj => <об’єкт модуля>)
40+
.catch(err => <помилка завантаження, наприклад якщо немає такого модуля>)
4141
```
4242

43-
Or, we could use `let module = await import(modulePath)` if inside an async function.
43+
Чи якщо усередині асинхронної функції, то можна використати `let module = await import(modulePath)`.
4444

45-
For instance, if we have the following module `say.js`:
45+
Наприклад, якщо у нас є такий модуль `say.js`:
4646

4747
```js
4848
// 📁 say.js
4949
export function hi() {
50-
alert(`Hello`);
50+
alert(`Привіт`);
5151
}
5252

5353
export function bye() {
54-
alert(`Bye`);
54+
alert(`Бувай`);
5555
}
5656
```
5757

58-
...Then dynamic import can be like this:
58+
...То динамічний імпорт може виглядати так:
5959

6060
```js
6161
let {hi, bye} = await import('./say.js');
@@ -64,35 +64,35 @@ hi();
6464
bye();
6565
```
6666

67-
Or, if `say.js` has the default export:
67+
А якщо в `say.js` вказаний типовий експорт:
6868

6969
```js
7070
// 📁 say.js
7171
export default function() {
72-
alert("Module loaded (export default)!");
72+
alert("Модуль завантажився (export default)!");
7373
}
7474
```
7575

76-
...Then, in order to access it, we can use `default` property of the module object:
76+
...То для доступу до нього нам слід узяти властивість `default` об’єкту модуля:
7777

7878
```js
7979
let obj = await import('./say.js');
8080
let say = obj.default;
81-
// or, in one line: let {default: say} = await import('./say.js');
81+
// або одним рядком: let {default: say} = await import('./say.js');
8282

8383
say();
8484
```
8585

86-
Here's the full example:
86+
Ось повний приклад:
8787

8888
[codetabs src="say" current="index.html"]
8989

9090
```smart
91-
Dynamic imports work in regular scripts, they don't require `script type="module"`.
91+
Динамічний імпорт працює в звичайних скриптах, він не вимагає вказівки `script type="module"`.
9292
```
9393

9494
```smart
95-
Although `import()` looks like a function call, it's a special syntax that just happens to use parentheses (similar to `super()`).
95+
Хоча `import()` і виглядає схожим на виклик функції, насправді це спеціальний синтаксис, так само, як, наприклад, `super()`.
9696
97-
So we can't copy `import` to a variable or use `call/apply` with it. It's not a function.
98-
```
97+
Тому ми не можемо скопіювати `import` в іншу змінну або викликати за допомогою `.call/apply`. Це не функція.
98+
```

1-js/13-modules/03-modules-dynamic-imports/say.view/index.html

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22
<script>
33
async function load() {
44
let say = await import('./say.js');
5-
say.hi(); // Hello!
6-
say.bye(); // Bye!
7-
say.default(); // Module loaded (export default)!
5+
say.hi(); // Привіт!
6+
say.bye(); // Бувай!
7+
say.default(); // Модуль завантажений (export default)!
88
}
99
</script>
10-
<button onclick="load()">Click me</button>
10+
<button onclick="load()">Натисни мене</button>
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
export function hi() {
2-
alert(`Hello`);
2+
alert(`Привіт`);
33
}
44

55
export function bye() {
6-
alert(`Bye`);
6+
alert(`Бувай`);
77
}
88

99
export default function() {
10-
alert("Module loaded (export default)!");
10+
alert("Модуль завантажений (export default)!");
1111
}

0 commit comments

Comments
 (0)