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

Mô-đun JavaScript

Các mô-đun đã được giới thiệu trong ES 2015. Các mô-đun đã được giới thiệu để chia mã thành các phần nhỏ hơn. Các mô-đun có thể chứa các lớp hoặc chức năng trong đó. Từ khóa xuất và nhập được sử dụng để xuất các biến, hàm, đối tượng và nhập chúng vào các tệp khác.

Lưu ý - Để chạy ví dụ này, bạn sẽ cần chạy một máy chủ localhost.

Sau đây là mã cho các mô-đun trong JavaScript

INDEX.html

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:blueviolet;
   }
</style>
</head>
<body>
<h1>JavaScript Modules</h1>
<button class="Btn">IMPORT</button>
<div class="result"></div>
<h3>Click on the above button to import module</h3>
<script src="script.js" type="module"></script>
<script src="sample.js" type="module"></script>
</body>
</html>

script.js

import test from './sample.js';
document.querySelector('.Btn').addEventListener('click',()=>{
   test();
})

sample.js

let resultEle = document.querySelector(".result");
export default function testImport(){
   resultEle.innerHTML = 'Module testImport has been imported';
}

Đầu ra

Mô-đun JavaScript

Khi nhấp vào nút 'NHẬP' -

Mô-đun JavaScript