Vai al contenuto principale
← ⚡ JavaScript & the browser·Modulo C3 · Lezione 3
CompitoInline approximation: declare a default-style 'Button' arrow function and a named-style TIMEOUT_MS constant. Then log 'Button:' + typeof Button and 'TIMEOUT_MS:' + TIMEOUT_MS.

Esportazione predefinita e denominata: quando ciascuna si adatta

75 XP7 min
Teoria

Default export — one main thing per file

// Button.js
export default function Button(props) { /* ... */ }

// or
export default class Button { /* ... */ }

// or
const Button = () => { /* ... */ };
export default Button;
// app.js
import Button from "./Button.js";    // no curlies — the importer names it

There's exactly one default export per file. The importer picks the local name — import Btn from "./Button.js" works too. That's the trade-off: convenience vs grep-ability.

Mixing default and named

// http.js
export default function fetchJSON(url) { /* main thing */ }
export const TIMEOUT_MS = 5000;
export function fetchText(url) { /* secondary thing */ }
import fetchJSON, { TIMEOUT_MS } from "./http.js";

The default is the "main thing." Named exports stand for everything else.

When to use which

  • Default — when the file is fundamentally about ONE thing (a React component, a class, the entry point of a library).
  • Named — when the file exports a set of utilities at the same level (format.js exports formatDate, formatCurrency, formatPercent).
  • Avoid mixing default + named in the same file once the named set grows past 2-3 things. Refactor the file into "main + sub-exports" or split it.

React convention

React components use default exports almost universally; hooks use named. That's just convention, not a rule, but it's so universal that breaking it costs reader-attention.

🔒

Iscriviti per iniziare a programmare

La teoria è aperta a tutti. Editor, anteprima e check si sbloccano con una prova gratuita di 7 giorni — carta richiesta, annullabile in qualsiasi momento.

Iscriviti — prova gratuita →

Le prime 10 lezioni di ogni percorso sono gratuite. Nessuna carta richiesta.

← PrecedenteProssima lezione →

Ricevi un consiglio Python o web al giorno — via email

Breve, scritto a mano, niente spam. Disiscriviti in un clic.