What is “export default” in JavaScript?
In default export the naming of import is completely independent and we can use any name we like.
I will illustrate this line with a simple example.
Let’s say we have three modules and an index.html file:
- modul.js
- modul2.js
- modul3.js
- index.html
File modul.js
export function hello() {
console.log("Modul: Saying hello!");
}
export let variable = 123;
File modul2.js
export function hello2() {
console.log("Module2: Saying hello for the second time!");
}
export let variable2 = 456;
modul3.js
export default function hello3() {
console.log("Module3: Saying hello for the third time!");
}
File index.html
<script type="module">
import * as mod from './modul.js';
import {hello2, variable2} from './modul2.js';
import blabla from './modul3.js'; // ! Here is the important stuff - we name the variable for the module as we like
mod.hello();
console.log("Module: " + mod.variable);
hello2();
console.log("Module2: " + variable2);
blabla();
</script>
The output is:
modul.js:2:10 -> Modul: Saying hello!
index.html:7:9 -> Module: 123
modul2.js:2:10 -> Module2: Saying hello for the second time!
index.html:10:9 -> Module2: 456
modul3.js:2:10 -> Module3: Saying hello for the third time!
So the longer explanation is:
'export default' is used if you want to export a single thing for a module.
So the thing that is important is "import blabla from './modul3.js'" - we could say instead:
"import pamelanderson from './modul3.js" and then pamelanderson();
. This will work just fine when we use 'export default' and basically this is it - it allows us to name it whatever we like when it is default.
P.S.: If you want to test the example - create the files first, and then allow CORS in the browser -> if you are using Firefox type in the URL of the browser: about:config -> Search for "privacy.file_unique_origin" -> change it to "false" -> open index.html -> press F12 to open the console and see the output -> Enjoy and don't forget to return the CORS settings to default.
P.S.2: Sorry for the silly variable naming
More information is in link2medium and link2mdn.
export
keyword details here. Currently it is not supported natively by any of the web browsers. – RBT