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.