Skip to content

Commit 891f42b

Browse files
committed
it updates dynamic modules article
1 parent bb54132 commit 891f42b

File tree

3 files changed

+33
-33
lines changed

3 files changed

+33
-33
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,61 +1,61 @@
1-
# Dynamic imports
1+
# Importações dinâmicas
22

3-
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.
44

5-
First, we can't dynamically generate any parameters of `import`.
5+
Primeiro, não podemos gerar dinamicamente quaisquer parâmetros de `import`.
66

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á:
88

99
```js
10-
import ... from *!*getModuleName()*/!*; // Error, only from "string" is allowed
10+
import ... from *!*getModuleName()*/!*; // Erro, apenas a partir de "string" é permitido
1111
```
1212

13-
Second, we can't import conditionally or at run-time:
13+
Segundo, não podemos importar condicionalmente ou em tempo de execução:
1414

1515
```js
1616
if(...) {
17-
import ...; // Error, not allowed!
17+
import ...; // Erro, não permitido!
1818
}
1919

2020
{
21-
import ...; // Error, we can't put import in any block
21+
import ...; // Erro, não podemos colocar import em qualquer bloco
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+
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.
2626

27-
But how can we import a module dynamically, on-demand?
27+
Mas como podemos importar um módulo dinamicamente, sob demanda?
2828

29-
## The import() expression
29+
## A expressão 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+
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.
3232

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:
3434

3535
```js
36-
let modulePath = prompt("Which module to load?");
36+
let modulePath = prompt("Qual módulo carregar?");
3737

3838
import(modulePath)
3939
.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>)
4141
```
4242

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.
4444

45-
For instance, if we have the following module `say.js`:
45+
Por exemplo, se temos o seguinte módulo `say.js`:
4646

4747
```js
4848
// 📁 say.js
4949
export function hi() {
50-
alert(`Hello`);
50+
alert(`Olá`);
5151
}
5252

5353
export function bye() {
54-
alert(`Bye`);
54+
alert(`Adeus`);
5555
}
5656
```
5757

58-
...Then dynamic import can be like this:
58+
...Então a importação dinâmica pode ser assim:
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+
Ou, se `say.js` tiver a exportação padrão>
6868

6969
```js
7070
// 📁 say.js
7171
export default function() {
72-
alert("Module loaded (export default)!");
72+
alert("Módulo carregado (exportação padrão)!");
7373
}
7474
```
7575

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:
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+
// Ou, em uma linha: let {default: say} = await import('./say.js');
8282

8383
say();
8484
```
8585

86-
Here's the full example:
86+
Aqui está o exemplo completo:
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+
Importações dinâmicas funcionam em scripts regulares, não requerem `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+
Embora `import()` pareça uma chamada de função, é uma sintaxe especial que, por acaso, utiliza parênteses (semelhante a `super()`).
9696
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.
9898
```

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

+3-3
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(); // Olá!
6+
say.bye(); // Adeus!
7+
say.default(); // Módulo carregado (exportação padrão)!
88
}
99
</script>
1010
<button onclick="load()">Click me</button>

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

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
export function hi() {
2-
alert(`Hello`);
2+
alert(`Olá`);
33
}
44

55
export function bye() {
6-
alert(`Bye`);
6+
alert(`Adeus`);
77
}
88

99
export default function() {

0 commit comments

Comments
 (0)