Módulos: import y export
Ningún proyecto real vive en un solo archivo. Así se reparte el código entre varios.
Modules: import and export
No real project lives in a single file. Here is how code gets split across several.
Hasta ahora todos tus ejemplos viven en un solo archivo. Funciona para tutoriales, pero un proyecto real —como los juegos de este sitio— tiene cientos de funciones: mezclarlas todas en un archivo se vuelve imposible de mantener.
Un módulo es, en la práctica, un archivo .js que
exporta las piezas que quiere compartir, para que otro archivo las
importe.
So far all your examples live in a single file. That works for tutorials, but a real project — like this site's games — has hundreds of functions: mixing them all into one file becomes impossible to maintain.
A module is, in practice, a .js file that
exports the pieces it wants to share, so another file can
import them.
Con export nombrado puedes compartir tantas cosas como quieras desde un mismo
archivo: funciones, variables, objetos.
With a named export you can share as many things as you like from the same
file: functions, variables, objects.
// archivo: puntaje.js
export function calcularBono(puntos) {
return Math.round(puntos * 0.1);
}
export const VIDAS_INICIALES = 3;
Desde otro archivo, import trae exactamente lo que necesitas, con el nombre
exacto entre llaves.
From another file, import brings in exactly what you need, with the exact
name inside braces.
// archivo: juego.js
import { calcularBono, VIDAS_INICIALES } from "./puntaje.js";
let vidas = VIDAS_INICIALES;
console.log("Bono:", calcularBono(1500));
Y en el HTML, el <script> que arranca todo debe
llevar type="module" para que import/export
funcionen:
And in the HTML, the <script> that starts it all
needs type="module" for import/export to work:
<script type="module" src="juego.js"></script>
Cuando un archivo tiene una cosa principal para compartir, se usa
export default. Al importarlo, le puedes poner el nombre que quieras —no tiene
que coincidir con nada.
When a file has one main thing to share, you use
export default. When importing it, you can name it whatever you like — it does
not have to match anything.
// archivo: jugador.js
export default class Jugador {
constructor(nombre) {
this.nombre = nombre;
this.puntos = 0;
}
}
// archivo: juego.js
import Jugador from "./jugador.js"; // sin llaves, y con el nombre que quieras
const j = new Jugador("Joaco");
Cómo y por qué dividir un proyecto en varios archivos, la diferencia entre
export nombrado y export default, y que el HTML necesita
type="module" para que todo esto funcione.
Última parada del curso: fechas y expresiones regulares en JavaScript, el equivalente a lo que ya viste del lado de Python.
How and why to split a project into several files, the difference between a named
export and export default, and that the HTML needs
type="module" for any of this to work.
Last stop of the course: dates and regular expressions in JavaScript, the counterpart to what you already saw on the Python side.