r/javascript • • Aug 27 '18

`export default` considered harmful

https://basarat.gitbooks.io/typescript/docs/tips/defaultIsBad.html
32 Upvotes

43 comments sorted by

View all comments

29

u/ryansmith94 Aug 27 '18

Interesting post, good to hear other people's opinions on this. Personally felt the "considered harmful" title was a little over the top, but I do use export default almost exclusively in TypeScript, unless I'm exporting interfaces or constants.

Like you, the CommonJS interop is a concern of mine, but with TS I'm compiling it down to ES5 so it's not an issue. The remainder of your issues seem to boil down to the need for additional syntax in places and poor tooling, not a lot you can do about the syntax at this point, but VS Code provides great tooling that's improving all the time, especially around the usage of default exports.

Whilst I don't agree with the title and don't think this post should put anyone off using default exports, some of the concerns here are certainly good to consider for people using default exports, so nice work 👍

1

u/bheklilr Aug 27 '18

I'm also writing exclusively in typescript, and I don't use default exports at all. It's mostly a personal preference thing though, although I do like the slightly better refactoring capabilities. I also am usually exporting multiple values from a module, having a default export doesn't make much sense.

As an example, if I'm working on a react+redux project and need to add a new connected component Comp, my process is:

  1. mkdir src/components/Comp

  2. touch src/components/Comp/index.tsx

  3. export interface CompProps {}

  4. export class CompComponent extends React.Component<CompProps>

  5. export const Comp = connect(...)(CompComponent)

  6. touch src/components/Comp/actions.tsx

  7. export const FOO_ACTION = '...'

  8. export type FooAction = ActionPayload<{ foo: string }>

  9. export const doFoo = (foo: string) => {...}

  10. export function reducer(state, action) {...}

(sorry for bad formatting, on mobile)

So at a minimum for a single component I might have 7 exports. For a non redux component I'd probably only have 2 or 3, depending on whether I needed a state types interface.

I could put many of these in their own files or something, but it becomes cumbersome very quickly. I don't necessarily use all of those exports, but when I do need them it's really handy to have vscode import them automatically for me.

Again, this is all personal style. To me, a default export is conveying the idea that a file only has a single thing you should use. I use default exports in those cases, but it's just not as common.

2

u/ryansmith94 Aug 28 '18

Yeah totally agree with your usage of default exports, I also tend to use them when I want to imply that it's the only thing that "should" be used from the file.