Difference between default export and named export - javascript

As I understand, exported functions can be imported with whatever name you please. For example, you can have a file functions.js that contains the code export default sayFruit and a main file main.js that contains the code import whatever from './functions.js. Then, whatever() outputs the same as sayFruit() in the functions.js file.
Now, is the fact that you can name the imported function whatever you would like the only difference between named export and default export?
Note: I suppose "named" export is the equivalente of writing export {functionName}.

You can only have a single default export. As such, when importing you can call it whatever you want. If you have multiple exports, you have to call them something when you export so you can specify in the file you're importing into which function/constant/etc you want from the source file. You can also rename named exports when you import them/
You can have a mix of default and named as well.
// asd.js
const Foo = "bar"
export default Foo
export const Baz = "bax"
// other file
import MyFoo, { Baz } from "./asd"
// other file with renamed Baz import
import MyFoo, { Baz: MyBaz } from "./asd"
but yea otherwise it's the same thing.
What I use as a reference:
https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export

Related

export is not working when try to destructure in javascript import

I have two file:
file A.js:
export default={
name:"sample"
}
file B.svelte:
import {name} from './A';
Error:
name is not export from A.js
There are two problems there:
That's now how you make the default export an object, you should remove the =.
import is not destructuring, they just have a superficial resemblance to each other. You can't destructure during an import.
I would make the export a named export:
export let name = "sample";
...which would work with your import. Changes to name by the source module will show up in the imported binding for it (imports are live bindings to the original export).
But if you don't want to do that, here's how you export an object as the default export:
export default {
name: "sample",
};
and then you have to import and destructure separately:
import obj from "./A.js";
const { name } = obj;
Note: The above is how standard JavaScript modules work according to specification. Bundlers may go beyond the spec when bundling code (for instance, may allow named import syntax when in fact you're destructuring a default exported objects), but if so, it's non-standard.

Is there any advantage to default export compared to named export? [duplicate]

I have referred all the questions in stackoverflow.
But none of the suggested why and when to use default export.
I just saw that default can be metioned "When there is only one export in a file"
Any other reason for using default export in es6 modules?
Some differences that might make you choose one over the other:
Named Exports
Can export multiple values
MUST use the exported name when importing
Default Exports
Export a single value
Can use any name when importing
This article does a nice job of explaining when it would be a good idea to use one over the other.
It's somewhat a matter of opinion, but there are some objective aspects to it:
You can have only one default export in a module, whereas you can have as many named exports as you like.
If you provide a default export, the programmer using it has to come up with a name for it. This can lead to inconsistency in a codebase, where Mary does
import example from "./example";
...but Joe does
import ex from "./example";
In contrast, with a named export, the programmer doesn't have to think about what to call it unless there's a conflict with another identifier in their module.¹ It's just
import { example } from "./example";
With a named export, the person importing it has to specify the name of what they're importing. They get a nice early error if they try to import something that doesn't exist.
If you consistently only use named exports, programmers importing from modules in the project don't have to think about whether what they want is the default or a named export.
¹ If there is a conflict (for instance, you want example from two different modules), you can use as to rename:
import { example as widgetExample } from "./widget/example";
import { example as gadgetExample } from "./gadget/example";
You should almost always favour named exports, default exports have many downsides
Problems with default exports:
Difficult to refactor or ensure consistency since they can be named anything in the codebase other than what its actually called
Difficult to analyze by automated tools or provide code intellisense and autocompletion
They break tree shaking as instead of importing the single function you want to use you're forcing webpack to import the entire file with whatever other dead code it has leading to bigger bundle sizes
You can't export more than a single export per file
You lose faster/direct access to imports
checkout these articles for a more detailed explanation:
https://blog.neufund.org/why-we-have-banned-default-exports-and-you-should-do-the-same-d51fdc2cf2ad
https://humanwhocodes.com/blog/2019/01/stop-using-default-exports-javascript-module/
https://rajeshnaroth.medium.com/avoid-es6-default-exports-a24142978a7a
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
// ex. importing a single named export
import { MyComponent } from "./MyComponent";
// ex. 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 = () => {}
You can also alias named imports, assign a new name to a named export as you import it, allowing you to resolve naming collisions, or give the export a more informative name.
import MyComponent as MainComponent from "./MyComponent";
You can also Import all the named exports onto an object:
import * as MainComponents from "./MyComponent";
// use MainComponents.MyComponent and MainComponents.MyComponent2 here
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";
// export
const MyComponent = () => {}
export default MyComponent;
The naming of import is completely independent in default export and we can use any name we like.
From MDN:
Named exports are useful to export several values. During the import, one will be able to use the same name to refer to the corresponding value.
Concerning the default export, there is only a single default export per module. A default export can be a function, a class, an object or anything else. This value is to be considered as the “main” exported value since it will be the simplest to import.
There aren't any definitive rules, but there are some conventions that people use to make it easier to structure or share code.
When there is only one export in the entire file, there is no reason to make it named.
Also, when your module has one main purpose, it could make sense to make that your default export. In those cases you can extra named exports
In react for example, React is the default export, since that is often the only part that you need. You don't always Component, so that's a named export that you can import when needed.
import React, {Component} from 'react';
In the other cases where one module has multiple equal (or mostly equal) exports, it's better to use named exports
import { blue, red, green } from 'colors';
1st Method:-
export foo; //so that this can be used in other file
import {foo} from 'abc'; //importing data/fun from module
2nd Method:-
export default foo; //used in one file
import foo from 'blah'; //importing data/fun from module
3rd Method:-
export = foo;
import * as foo from 'blah';
The above methods roughly compile to the following syntax below:-
//all export methods
exports.foo = foo; //1st method
exports['default'] = foo; //2nd method
module.exports = foo; //3rd method
//all import methods
var foo = require('abc').foo; //1st method
var foo = require('abc')['default']; //2nd method
var foo = require('abc'); //3rd method
For more information, visit to Default keyword explaination
Note:- There can be only one export default in one file.
So whenever we are exporting only 1 function, then it's better to use default keyword while exporting
EASIEST DEFINITION TO CLEAR CONFUSIONS
Let us understand the export methods, first, so that we can analyze ourselves when to use what, or why do we do what we do.
Named exports: One or more exports per module. When there are more than one exports in a module, each named export must be restructured while importing. Since there could be either export in the same module and the compiler will not know which one is required unless we mention it.
//Named export , exporting:
export const xyz = () =>{
}
// while importing this
import {xyx} from 'path'
or
const {xyz} = require(path)
The braces are just restructuring the export object.
On the other hand , default exports are only one export per module , so they are pretty plain.
//exporting default
const xyz =() >{
};
export default xyz
//Importing
import xyz from 'path'
or
const xyz = require(path)
I hope this was pretty simple to understand, and by now you can understand why you import React modules within braces...
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
// ex. importing a single named export
import { MyComponent } from "./MyComponent";
// ex. 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:
// use MainComponents.MyComponent and MainComponents.MyComponent2 here
import * as MainComponents from "./MyComponent";
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";
// export
const MyComponent = () => {}
export default MyComponent;
Note: The naming of import is completely independent in default export and we can use any name we like.
Here's a great answer that explains default and named imports in ES6

How does one "implicitly export an entire module"?

The following is a section from MDN's reference on the JavaScript import statement (with added emphasis):
Import a single export from a module
Given an object or value named myExport which has been exported from the module my-module either implicitly (because the entire module is exported) or explicitly (using the export statement), this inserts myExport into the current scope.
import {myExport} from '/modules/my-module.js';
I know what it means for an object or value to have been exported from a module explicitly (using the export statement), but how can they be exported implicitly (impliedly without using an export statement)? What does it mean for an "entire module" to be exported?
I think the wording on this statement is somewhat confusing, assuming I understand it correctly. I think what they mean by "explicitly" would be explicitly named, e.g.
export { foo };
// or others
export var foo;
export function foo(){}
export class foo {}
export { foo } from "./foo.js";
whereas implicitly would be one that is not explicitly named, like
export * from "./foo.js";
where then doing
import { foo } from "./mod.js";
would work as long as mod is re-exporting foo from the foo.js file.
lets make it this way
Given an object or value named myExport which has been exported implicitly (because the entire module is exported) from a module
or
Given an object or value named myExport which has been exported explicitly (using the export statement) from a module
so i can export an object or func like this
// ./modules/my-module.js
export default UserApi = {
myExport: function() {
console.log(please make api call)
}
}
// ./otherfile.js
import {myExport} from '/modules/my-module.js';
i never explicitly export myExport but you can import myExport without importing UserApi which i explicitly export

ES6 - exporting named export without importing them?

Let's assume I have a folder with two files called ModuleA.js and ModuleB.js that looks like this:
ModuleA.js
export default {
someKey: 'Hello, world',
};
ModuleB.js
export const foo = 'bar';
export const another = 'variable';
Then I have an index.js file that I would like to perform named export on those modules without writing the import statement. I know how to do it with ModuleA:
export { default as ModuleA } from './ModuleA';
But how can I import the name exports and export them in one line without writing e.g.?
import * as _ModuleB from './ModuleB'
export const ModuleB = _ModuleB;
You can only reexport everything:
export * from "./ModuleB";
But you can't group that under a new namespace without importing & exporting. There is a proposal to change that.

Difference between export const foo, export default foo and module.exports = foo

I am really confused about:
export const foo
export default foo
module.exports = foo;
I know these are very basic but could someone please differentiate and explain these to me. I really want to understand.
Let take each of these one by one.
export const
export const foo
This is ES6 export syntax for a named export. You can have many named exports. It says that you want to export the value of the variable foo and you are also declaring that symbol to be const in this module.
You can't actually use export const foo all by itself just like you can use const foo; all by itself. Instead, you would have to assign something to it:
export const foo = 12;
The const applies only to within the module itself. It does not affect what someone can do with the value once they've imported the value from the module on the other end because at the other end (where its imported), it's value is copied into another variable. If that other variable is created with the import statement, then it is automatically const on the import side (you cannot assign to it) no matter what it was declared on the export side.
This could be imported as either of these:
import {foo as localFoo} from 'lib';
import {foo} from 'lib';
The first imports the foo property of the module into a localFoo named variable.
The second imports the foo property of the module into a foo named variable.
export default
export default foo
This is also ES6 syntax and says that you also want to export the value of the variable foo and you want that to be the default export value so if someone imports just the module and not any properties of the module, this is the variable they will get. You can only have one default export per module.
Internally, the default export is really just a named export with the special name default assigned:
import localVar from 'myLib';
This will get the default export from myLib and assign it's value to a locally declared variable named localVar. The above is a shorthand for this:
import { default as localVar } from 'lib';
So, the default export just allows you to have a shortcut import for one particular export. The ES6 import/export syntax was designed to make the syntax as brief as possible for the default import/export. But, for obvious reasons, there is only one default property per module.
module.exports
// inside of myModule
module.exports = foo;
This is node.js syntax for exporting the value of the variable foo and you're exporting it at the top level. When someone uses this module:
let x = require('myModule');
console.log(x); // will show the value of `foo` from the previous module
This is not ES6 syntax, but is regular ES5-compatible syntax using the module.exports and require() infrastructure built into node.js.
The export statement is used to export functions, objects or primitives from a given file (or module).
Named Exports
This is a named export in ES6 javascript
export const foo
which is imported like:
import { foo } from 'path'
Default Export
This is a default export (This can be imported using any name)
export default foo
which is imported like so:
import bar from 'path'
This is commonjs export which is used in nodejs programs.
module.exports = foo;
which is imported like:
var foo = require('path')
For more details
export const foo : exports constants (ES6)
export default foo : exports object (ES6)
Above statements are ECMA Script 2015 (aka ES6) implementation.
In an normal ES6 JS file one can export any object(variable) or constants. Pls note that you cannot change constant reference, though internal structure can be modified(weird).
In ES6 one can have multiple exports in module(script file). which can be added in calling script as
import {Obj1, Obj2} from module_file
coming to export default, One can have only one export default in module. and while importing when exact names are not defined default is been picked up.
module.exports = foo; is older implementation and it is same as export default. except it is imported with require statement instead of import
for more refer https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export

Categories