TypeScriptModules and namespaces
Default export in TypeScript
4 A default export, imported under any name
easyWrite a module whose main thing is a default export. Import it elsewhere and use it. Note what a default export gives you and what it costs.
Stuck? Three hints, smallest first
- 1. A file may have at most one
export default. - 2. The importer chooses the name, which is flexible and also means two files can call the same thing differently.
- 3. A default and named exports can live in the same file.
The real answer, across 2 files. Type-checked by the compiler at build time; not runnable in a browser, because a panel cannot contain import or export.
// One default export, plus a named one alongside it.
export type Level = 'info' | 'warn';
export default class Logger {
private lines: string[] = [];
log(level: Level, message: string): this {
this.lines.push(`[${level}] ${message}`);
return this;
}
get output(): readonly string[] {
return this.lines;
}
}
export const DEFAULT_LEVEL: Level = 'info';
// The name is the importer's choice: no braces, so this is the default.
import Log, { DEFAULT_LEVEL, type Level } from './logger.js';
const log = new Log();
log.log(DEFAULT_LEVEL, 'started').log('warn', 'low on seats');
for (const line of log.output) console.log(line);
// Nothing stops a second file calling it something else entirely, which is
// the main argument against default exports on a big team.
const level: Level = 'warn';
console.log('level:', level);
const same = (a: unknown, b: unknown): boolean =>
JSON.stringify(a) === JSON.stringify(b);
function test(name: string, got: unknown, want: unknown): void {
console.log(
(same(got, want) ? 'ok ' : 'FAIL ') + name +
(same(got, want) ? '' : ` got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`)
);
}
type Level = 'info' | 'warn';
class Logger {
private lines: string[] = [];
log(level: Level, message: string): this {
this.lines.push(`[${level}] ${message}`);
return this;
}
get output(): readonly string[] {
return this.lines;
}
}
const DEFAULT_LEVEL: Level = 'info';
// A default export is really just "the one thing this file is about".
// Here that is the class itself, so we use it directly.
const log = new Logger();
log.log(DEFAULT_LEVEL, 'started').log('warn', 'low on seats');
for (const line of log.output) console.log(line);
test('two lines were logged', log.output.length, 2);
test('the default level was used', log.output[0], '[info] started');
test('the second line', log.output[1], '[warn] low on seats');
test('chaining worked', new Logger().log('info', 'a').log('info', 'b').output.length, 2);
Output
Worth having an opinion here. A default export lets each importer pick its own name, which sounds convenient and means the same class can appear as Log, Logger and L across three files. Named exports keep one name everywhere and are easier to search for. Most large codebases now prefer named exports for exactly that reason.