What would be the advantage of named exports over other exports?

Question

what would be the advantage of named exports over other exports?

Answer

Name exports provide us the possibility to only import the necessary piece of code from another file without having to import more than needed if we were to use the default keyword, that will mean that everything in that default export will be available, on the other hand, using module.exports like it used to be before ES6+ would have a similar drawback since it will create a single object that will contain the exported content when required in a file, for example:

module.exports

const threeFunc = {};
threeFunc.funcOne = () => {...};

threeFunc.functwo = () => {...};

threeFunc.funcThree = () => {...};

module.exports = threeFunc.;

which in our importing file we will do:

const threeFunc = require('./threeFunc.js');

that will actually be like saying:

const threeFunc = {
  funcOne = () => {...},
  functwo = () => {...},
  funcThree = () => {...}
};

the equivalent in ES6+ is export default, but now we also have easy access to a single item in another file, as we were mentioning, unsing named exports:

export const funcOne = () => {...};

export  const functwo = () => {...};

export const funcThree = () => {...};

in this case, we are still exporting the three but if we only need one from the file you do not need to load all of them and delaying loading time by adding weight with the other two functions by using:

import { funcTwo } from './threeFunc';

Now, yes, we can do the same thing if we exported them all with export default and write:

import threeFunc.funcTwo from './threeFunc';

but what if we do not want to have all the functions capable to be exported:

const funcOne = () => {...};

export  const functwo = () => {...};

const funcThree = () => {...};

I only want to have funcTwo to be available outside of the file, named exports provide that possibilty.

7 Likes

Hi!, @axelkaban.
Does that mean I could have a single .js file with several React components and export them as required?

You could do that but that beats the purpose of react being modular.

4 Likes

Not sure if you learn that later on in the React course, but you can also export things like that:

const foo = 1;
let bar = 2;

function baz() {
  console.log("baz");
}

export { foo, bar, baz };

So if you need to import it now, you could do:

import { foo, bar, baz } from "./directory";

If you want to export everything in a file, you can do:

const foo = 1;
let bar = 2;

function baz() {
  console.log("baz");
}

export *;

And if you want to import everything, you could do:

import * from "./directory";
6 Likes