Why would I want to combine named exports with default exports?


#1

Question

Why would I want to combine named exports with default exports?

Answer

We combine named exports and default exports when we want to give a module the ability to define the default export of the module and other, potentially useful, pieces of a module (the named exports).

For example, these other pieces may be the internals of a private variable where we have access to part of a private variable, but not the entire private variable.

Example:
moduleToExport.js

const uppercaseName = function (name) {
  return name.toUpperCase();
}

const myDefaultExport = {
  //...
}


class Animal {
  constructor(name){
    this._name = name;
  }
  get name () {
    return uppercaseName(this._name);
  }
}


export default myDefaultExport; //default export is the `myDefaultExport` object
export {Animal}; //named export `Animal` class, not exporting the `uppercaseName` function

main.js

import myDefaultExport from './moduleToExport.js'; //importing default module `myDefaultExport`
import {Animal} from './moduleToExport.js'; //importing a named module, `Animal`

const animal = new Animal('test');
console.log(animal.name); //logs `TEST` to the console, uses the private `uppercaseName` function even though we don't have access to `uppercaseName` through our imported `Animal` module and cannot call it explicitly

#2

I am using this one in my own projects on classes.
export default MyClass;
import MyClass from './moduleToExport.js';

I am wondering. Is there realy a diffrence between these 2 ways of exporting/importing ?

export {MyClass};
import {MyClass} from './moduleToExport.js';
and
export default MyClass;
import MyClass from './moduleToExport.js';
seem completely the same in my experiences.