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

3

u/allicanseenow Aug 27 '18

Title is misleading and can hinder inexperienced users from following this nice coding convention.

This totally depends on the situation. Just an example in React where most of the time you will write components, "export default class" is and always the most accurate and concise behavior because:

  • You never rename the class, and you should always have 1 class in a file. That's also how you do should consider doing in OOP by the way.

  • If there is a sub class, put it in a separate files

For backend, where you can export a lot of APIs from a file, it is better if you put exported components in an object, just like how you do it with module.exports.

3

u/Klathmon Aug 27 '18

Or one of my favorite conventions:

export class Thing extends...

// later...

export default connect(Thing)(...

Your "usable" component is always default exported, and the un-connected component is always exported by name for testing.

3

u/Akkuma Aug 27 '18

The way we've been doing it where I work is you have /components/SomeComponent under there is a SomeComponent.js, which is written as a "plain component" without HOC wrapping it. So it'll be something like export default class. The index.js then pulls in that component and wraps it as necessary with HOC components and is an export default connect(SomeComponent).

1

u/Klathmon Aug 27 '18

That was the same setup I was using before I read about the convention I put above, which I really enjoyed and it reduces the amount of boilerplate and puts the connect call in the same file.

When you use selectors (located elsewhere), and action creators (also located elsewhere) with redux, it makes a lot of sense as your actual call to connect is normally only a few lines if that, and it always felt kind of silly to have a full file for that.

It makes more sense if you are doing ad-hoc "selectors" in your call to connect, or are combining several HOCs at once, as then it warrants the larger file, but that's more of a difference in overall architecture.

But in the end, as long as you have a plan and stick to it it's fine, the problems show up when you don't have any direction on how to structure things and every file ends up being different.