You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Export and import statements that we covered in previous chapters are called "static". The syntax is very simple and strict.
3
+
As declarações de importação e exportação que abordamos nos capítulos anteriores são chamadas de "estáticas". A sintaxe é bem simples e rígida.
4
4
5
-
First, we can't dynamically generate any parameters of`import`.
5
+
Primeiro, não podemos gerar dinamicamente quaisquer parâmetros de`import`.
6
6
7
-
The module path must be a primitive string, can't be a function call. This won't work:
7
+
O caminho do módulo deve ser uma string primitiva, não pode ser uma chamada de função. Isso não funcionará:
8
8
9
9
```js
10
-
import ... from*!*getModuleName()*/!*; //Error, only from "string" is allowed
10
+
import ... from*!*getModuleName()*/!*; //Erro, apenas a partir de "string" é permitido
11
11
```
12
12
13
-
Second, we can't import conditionally or at run-time:
13
+
Segundo, não podemos importar condicionalmente ou em tempo de execução:
14
14
15
15
```js
16
16
if(...) {
17
-
import ...; //Error, not allowed!
17
+
import ...; //Erro, não permitido!
18
18
}
19
19
20
20
{
21
-
import ...; //Error, we can't put import in any block
21
+
import ...; //Erro, não podemos colocar import em qualquer bloco
22
22
}
23
23
```
24
24
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
+
Isso ocorre porque `import`/`export`têm como objetivo fornecer uma estrutura básica para a organização do código. Isso é algo bom, pois a estrutura do código pode ser analisada, os módulos podem ser reunidos e agrupados em um único arquivo por ferramentas especiais, e as exportações não utilizadas podem ser removidas ("tree-shaken"). Isso é possível apenas porque a estrutura de importações/exportações é simples e fixa.
26
26
27
-
But how can we import a module dynamically, on-demand?
27
+
Mas como podemos importar um módulo dinamicamente, sob demanda?
28
28
29
-
## The import() expression
29
+
## A expressão import()
30
30
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
+
A expressão `import(módulo)`carrega o módulo e retorna uma promise que é resolvida para um objeto de módulo contendo todas as suas exportações. Pode ser chamado de qualquer lugar no código.
32
32
33
-
We can use it dynamically in any place of the code, for instance:
33
+
Podemos utilizá-lo dinamicamente em qualquer lugar do código , por exemplo:
34
34
35
35
```js
36
-
let modulePath =prompt("Which module to load?");
36
+
let modulePath =prompt("Qual módulo carregar?");
37
37
38
38
import(modulePath)
39
39
.then(obj=><module object>)
40
-
.catch(err=><loading error, e.g. if no such module>)
40
+
.catch(err=><Erro de carregamento, por exemplo, se o módulo não existir>)
41
41
```
42
42
43
-
Or, we could use `let module = await import(modulePath)`if inside an async function.
43
+
Ou, poderíamos usar `let module = await import(caminhoDoModulo)`se estiver dentro de uma função assíncrona.
44
44
45
-
For instance, if we have the following module`say.js`:
45
+
Por exemplo, se temos o seguinte módulo`say.js`:
46
46
47
47
```js
48
48
// 📁 say.js
49
49
exportfunctionhi() {
50
-
alert(`Hello`);
50
+
alert(`Olá`);
51
51
}
52
52
53
53
exportfunctionbye() {
54
-
alert(`Bye`);
54
+
alert(`Adeus`);
55
55
}
56
56
```
57
57
58
-
...Then dynamic import can be like this:
58
+
...Então a importação dinâmica pode ser assim:
59
59
60
60
```js
61
61
let {hi, bye} =awaitimport('./say.js');
@@ -64,35 +64,35 @@ hi();
64
64
bye();
65
65
```
66
66
67
-
Or, if`say.js`has the default export:
67
+
Ou, se`say.js`tiver a exportação padrão>
68
68
69
69
```js
70
70
// 📁 say.js
71
71
exportdefaultfunction() {
72
-
alert("Module loaded (export default)!");
72
+
alert("Módulo carregado (exportação padrão)!");
73
73
}
74
74
```
75
75
76
-
...Then, in order to access it, we can use `default`property of the module object:
76
+
...Então, para acessá-lo, podemos usar a propriedade `default`do objeto do módulo:
77
77
78
78
```js
79
79
let obj =awaitimport('./say.js');
80
80
let say =obj.default;
81
-
//or, in one line: let {default: say} = await import('./say.js');
81
+
//Ou, em uma linha: let {default: say} = await import('./say.js');
82
82
83
83
say();
84
84
```
85
85
86
-
Here's the full example:
86
+
Aqui está o exemplo completo:
87
87
88
88
[codetabs src="say" current="index.html"]
89
89
90
90
```smart
91
-
Dynamic imports work in regular scripts, they don't require `script type="module"`.
91
+
Importações dinâmicas funcionam em scripts regulares, não requerem `script type="module"`.
92
92
```
93
93
94
94
```smart
95
-
Although `import()` looks like a function call, it's a special syntax that just happens to use parentheses (similar to `super()`).
95
+
Embora `import()` pareça uma chamada de função, é uma sintaxe especial que, por acaso, utiliza parênteses (semelhante a `super()`).
96
96
97
-
So we can't copy `import` to a variable or use `call/apply` with it. It's not a function.
97
+
Portanto, não podemos copiar `import` para uma variável ou usar `call/apply` com ele. Não é uma função.
0 commit comments