ในไฟล์หนึ่งสามารถมี default export ได้เพียงอันเดียว และสามารถตั้งชื่ออะไรก็ได้เมื่อ import เข้าไปในไฟล์อื่น แต่ named exports สามารถมีหลายตัวในไฟล์เดียว และต้อง import ด้วยชื่อที่ใช้ export
ตัวอย่าง
<!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">คลิกที่นี่</button>
<h3>คลิกปุ่มด้านบนเพื่อ export ฟังก์ชันเป็น named และ 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();
})
ผลลัพธ์
โค้ดข้างต้นจะสร้างผลลัพธ์ดังนี้:

เมื่อคลิกปุ่ม ‘คลิกที่นี่’:
