Skip to content

Commit c8f6fc6

Browse files
authored
Merge pull request #295 from vplentinax/dynamics
Dynamic imports
2 parents 0d47ca6 + 7e30364 commit c8f6fc6

File tree

3 files changed

+33
-33
lines changed

3 files changed

+33
-33
lines changed
Lines changed: 27 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,61 +1,61 @@
1-
# Dynamic imports
1+
# Importaciones 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+
Las declaraciones de exportación e importación que cubrimos en capítulos anteriores se denominan "estáticas". La sintaxis es muy simple y estricta.
44

5-
First, we can't dynamically generate any parameters of `import`.
5+
Primero, no podemos generar dinámicamente ningún parámetro de `import`.
66

7-
The module path must be a primitive string, can't be a function call. This won't work:
7+
La ruta del módulo debe ser una cadena primitiva, no puede ser una llamada de función. Esto no funcionará:
88

99
```js
10-
import ... from *!*getModuleName()*/!*; // Error, only from "string" is allowed
10+
import ... from *!*getModuleName()*/!*; // Error, from sólo permite "string"
1111
```
1212

13-
Second, we can't import conditionally or at run-time:
13+
En segundo lugar, no podemos importar condicionalmente o en tiempo de ejecución:
1414

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

2020
{
21-
import ...; // Error, we can't put import in any block
21+
import ...; // Error, no podemos poner importación en ningún bloque.
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+
Esto se debe a que `import`/`export` proporcionan una columna vertebral para la estructura del código. Eso es algo bueno, ya que la estructura del código se puede analizar, los módulos se pueden reunir y agrupar en un archivo mediante herramientas especiales, las exportaciones no utilizadas se pueden eliminar ("tree-shaken"). Eso es posible solo porque la estructura de las importaciones / exportaciones es simple y fija.
2626

27-
But how can we import a module dynamically, on-demand?
27+
Pero, ¿cómo podemos importar un módulo dinámicamente, a petición?
2828

29-
## The import() expression
29+
## La expresión 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+
La expresión `import(module)` carga el módulo y devuelve una promesa que se resuelve en un objeto de módulo que contiene todas sus exportaciones. Se puede llamar desde cualquier lugar del código.
3232

33-
We can use it dynamically in any place of the code, for instance:
33+
Podemos usarlo dinámicamente en cualquier lugar del código, por ejemplo:
3434

3535
```js
36-
let modulePath = prompt("Which module to load?");
36+
let modulePath = prompt("¿Qué modulo cargar?");
3737

3838
import(modulePath)
3939
.then(obj => <module object>)
4040
.catch(err => <loading error, e.g. if no such module>)
4141
```
4242

43-
Or, we could use `let module = await import(modulePath)` if inside an async function.
43+
O, podríamos usar `let module = await import(modulePath)` si está dentro de una función asíncrona.
4444

45-
For instance, if we have the following module `say.js`:
45+
Por ejemplo, si tenemos el siguiente módulo `say.js`:
4646

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

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

58-
...Then dynamic import can be like this:
58+
...Entonces la importación dinámica puede ser así:
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+
O, si `say.js` tiene la exportación predeterminada:
6868

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

76-
...Then, in order to access it, we can use `default` property of the module object:
76+
...Luego, para acceder a él, podemos usar la propiedad `default` del objeto del 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+
// o, en una línea: let {default: say} = await import('./say.js');
8282

8383
say();
8484
```
8585

86-
Here's the full example:
86+
Aquí está el ejemplo 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+
Las importaciones dinámicas funcionan en scripts normales, no requieren `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+
Aunque `import()` parece una llamada de función, es una sintaxis especial que solo usa paréntesis (similar 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+
Por lo tanto, no podemos copiar `import` a una variable o usar `call/apply` con ella. No es una función.
9898
```

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

Lines changed: 3 additions & 3 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(); // ¡Hola!
6+
say.bye(); // ¡Adiós!
7+
say.default(); // Módulo cargado (export default)!
88
}
99
</script>
1010
<button onclick="load()">Click me</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(`Hola`);
33
}
44

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

99
export default function() {
10-
alert("Module loaded (export default)!");
10+
alert("Módulo cargado (export default)!");
1111
}

0 commit comments

Comments
 (0)