https://basarat.gitbook.io/typescript/main-1/defaultisbad
foo.ts
class Foo {
}
export default Foo;
You can import the class like this bar.ts
import Foo from "./foo";
There a few maintainability concerns with export default
- refactoring
Foo
will not rename it inbar.ts
- You can't export more stuff from
foo.ts
without juggling import syntax
It is much better to use simple export + destructured import
foo.ts
export class Foo {
}
bar.ts
import { Foo } from "./foo";
- Poor discoverability - using intellisense to explore a module
- Autocomplete
import {/*here*/} from "./foo";
works - CommonJS interop - dont have to use
const {default} = require('module/foo');
- Typo protection
- TypeScript auto-import - quick fixes works better
- Re-exporting from npm packages forces you to name default export manually
- Require an extra line to
export default foo
- Dynamic imports - dont have to have
default
but use dynamic name instead
const HighCharts = await import('https://code.highcharts.com/js/es-modules/masters/highcharts.src.js');
HighCharts.default.chart('container', { ... }); // Notice `.default`
vs
const {HighCharts} = await import('https://code.highcharts.com/js/es-modules/masters/highcharts.src.js');
HighCharts.chart('container', { ... }); // Notice `.default`