Default exports vs Named exports in JavaScript.

JavascriptWeb DevelopmentObject Oriented Programming

There can be only one default export per file and we can assign it any name when importing it to the other file. However, there can be multiple named exports in a file and they are imported using the name that were used to export.

Following is the code showing difference between default exports and named exports in JavaScript −

Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
</style>
</head>
<body>
<h1>Default export vs Named Export</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above export function as named and default export</h3>
<script src="script.js" type="module">
</script>
</body>
</html>

sample.js

export default function testImport(){
   return 'Module testImport has been imported'+'';
}
export function tellTime(){
   return new Date();
}

script.js

import defaultExport from "./sample.js";
import {tellTime} from "./sample.js";
let resultEle = document.querySelector('.result');
document.querySelector('.Btn').addEventListener('click',()=>{
   resultEle.innerHTML+=defaultExport();
   resultEle.innerHTML+=tellTime();
})

Output

The above code will produce the following output −

On clicking the ‘CLICK HERE’ button −

raja
Published on 17-Jul-2020 07:09:20
Advertisements