Computer >> Máy Tính >  >> Lập trình >> Javascript

Xuất mặc định so với xuất được đặt tên trong JavaScript.


Chỉ có thể có một lần xuất mặc định cho mỗi tệp và chúng tôi có thể gán bất kỳ tên nào cho nó khi nhập nó vào tệp khác. Tuy nhiên, có thể có nhiều bản xuất được đặt tên trong một tệp và chúng được nhập bằng tên đã được sử dụng để xuất.

Sau đây là mã hiển thị sự khác biệt giữa xuất mặc định và xuất được đặt tên trong JavaScript -

Ví dụ

<!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();
})

Đầu ra

Đoạn mã trên sẽ tạo ra kết quả sau -

Xuất mặc định so với xuất được đặt tên trong JavaScript.

Khi nhấp vào nút 'BẤM VÀO ĐÂY' -

Xuất mặc định so với xuất được đặt tên trong JavaScript.