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
+
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.
4
4
5
-
First, we can't dynamically generate any parameters of`import`.
5
+
Primero, no podemos generar dinámicamente ningún parámetro de`import`.
6
6
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á:
8
8
9
9
```js
10
-
import ... from*!*getModuleName()*/!*; // Error, only from "string" is allowed
10
+
import ... from*!*getModuleName()*/!*; // Error, from sólo permite "string"
11
11
```
12
12
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:
14
14
15
15
```js
16
16
if(...) {
17
-
import ...; // Error, not allowed!
17
+
import ...; //¡Error, no permitido!
18
18
}
19
19
20
20
{
21
-
import ...; // Error, we can't put import in any block
21
+
import ...; // Error, no podemos poner importación en ningún bloque.
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
+
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.
26
26
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?
28
28
29
-
## The import() expression
29
+
## La expresión 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
+
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.
32
32
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:
34
34
35
35
```js
36
-
let modulePath =prompt("Which module to load?");
36
+
let modulePath =prompt("¿Qué modulo cargar?");
37
37
38
38
import(modulePath)
39
39
.then(obj=><module object>)
40
40
.catch(err=><loading error, e.g. if no such module>)
41
41
```
42
42
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.
44
44
45
-
For instance, if we have the following module`say.js`:
45
+
Por ejemplo, si tenemos el siguiente módulo`say.js`:
46
46
47
47
```js
48
48
// 📁 say.js
49
49
exportfunctionhi() {
50
-
alert(`Hello`);
50
+
alert(`Hola`);
51
51
}
52
52
53
53
exportfunctionbye() {
54
-
alert(`Bye`);
54
+
alert(`Adiós`);
55
55
}
56
56
```
57
57
58
-
...Then dynamic import can be like this:
58
+
...Entonces la importación dinámica puede ser así:
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
+
O, si`say.js`tiene la exportación predeterminada:
68
68
69
69
```js
70
70
// 📁 say.js
71
71
exportdefaultfunction() {
72
-
alert("Module loaded (export default)!");
72
+
alert("Módulo cargado (export default)!");
73
73
}
74
74
```
75
75
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:
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
+
//o, en una línea: let {default: say} = await import('./say.js');
82
82
83
83
say();
84
84
```
85
85
86
-
Here's the full example:
86
+
Aquí está el ejemplo 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
+
Las importaciones dinámicas funcionan en scripts normales, no requieren `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
+
Aunque `import()` parece una llamada de función, es una sintaxis especial que solo usa paréntesis (similar 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
+
Por lo tanto, no podemos copiar `import` a una variable o usar `call/apply` con ella. No es una función.
0 commit comments