Member-only story
Named Exports vs Default Exports
If you are working on Node Js/javascripts /ES module, There are high chances that you might have imported/exported any const, class , variable etc. and some time you might have seen statement like
import React from "react";
import { MDBInput } from "mdbreact";
import * as sentry from "sentry"
So in above example , one we are exporting without curly braces and one with curly braces and one with *. And we get confused what is what ? and what are difference between these 3 type of import statement declaration.
First statement is default export, second statement is named export , third statement is alias export.
Named Export: (export)
With named exports, one can have multiple named exports per file. Then import the specific exports they want surrounded in braces. The name of imported module has to be the same as the name of the exported module.
// imports
// importing a single named export
import { MyComponent } from "./MyComponent";// importing multiple named exports
import { MyComponent, MyComponent2 } from "./MyComponent";// ex. giving a named import a different name by using "as":
import { MyComponent2 as MyNewComponent } from "./MyComponent";// exports from ./MyComponent.js file
export const MyComponent = () => {}
export const MyComponent2 = () => {}
Import all the named exports onto an object:
import * as MainComponents from "./MyComponent";
// use MainComponents.MyComponent and MainComponents.MyComponent2
here
Default Export: (export default)
One can have only one default export per file. When we import we have to specify a name and import like:
// import
import MyDefaultComponent from "./MyDefaultExport";in MyDefaultExport.js
export default MyComponent {
}
The naming of import is completely independent in default export and we can use any name we like.
We can export function,const and object etc and use them as per below example in case of named export.
// module "my-module.js"
function cube(x) {
return x * x * x;
}
const foo = Math.PI + Math.SQRT2;
var graph = {
options: {
color:'white',
thickness:'2px'
},
draw: function() {
console.log('From graph draw function');
}
}
export { cube, foo, graph };
Then we can call them like this
import { cube, foo, graph } from './my-module.js';
graph.options = {
color:'blue',
thickness:'3px'
};
graph.draw();
console.log(cube(3)); // 27
console.log(foo); // 4.555806215962888
But in case of default export only one
// module "my-module.js"
export default function cube(x) {
return x * x * x;
}
Then, in another script, it is straightforward to import the default export:
import cube from './my-module.js';
console.log(cube(3)); // 27
So it is good to understand this things , it helps us to understand and become a good programmer.