DEV Community

JavaScript debate : named imports VS default imports

Nathanaël CHERRIER on October 17, 2019

A debate on the type of import we use in JavaScript has recently appeared. Same kind of debate than the one with semicolon. It works whichever yo...
Collapse
 
eaich profile image
Eddie

Great article! I agree that different situations may call for different techniques.

If I expect the functions in the module to be used often and holistically, I may use default export at the end of my file instead of defining exports on each function:

// Math.js
function add(x, y) {
// ...
}

export default {
  add,
  subtract,
  multiply
}

import Math from './Math.js';

const result = Math.add(x, y);

...and I'll name my module something generic like Math. Or in the example you showed above, Rotate instead of detectRotation.

Named exports may be more readable to some, but sometimes it may be preferable to see the function and the module in which it came from.

import { detect as detectRotation } from './Rotate.js';
detectionRotation();
// vs.
import Rotate from './Rotate.js';
Rotate.detect();
Collapse
 
mindsers profile image
Nathanaël CHERRIER

Thanks!

And yes, I agree that is a great way to export utils functions. 👍🏽

Collapse
 
seanmclem profile image
Seanmclem

I'm starting to prefer named imports. Defaults seem to create inconsistentcy for me so I have been trying to avoid them lately.

Collapse
 
mindsers profile image
Nathanaël CHERRIER • Edited

Same feeling. I think a team must define some rules to be able to use default imports efficiently : what can we expect to have from a default import, etc. But the rules will change from a project to another.
Named imports allow to avoid having to defines those rules. It's easier to integrate a new dev on your team.