Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

โมดูล (Modules) ใน JavaScript - แบ่งโค้ดเป็นไฟล์เล็กๆ

JavaScript Modules (ES Modules) ถูกนำเข้ามาใน ES2015 (ES6) เพื่อช่วยจัดระเบียบโค้ดโดยแบ่งเป็นไฟล์เล็กๆ ที่สามารถนำกลับมาใช้ซ้ำได้ ใช้คีย์เวิร์ด export เพื่อส่งออก และ import เพื่อนำเข้า

คุณสมบัติหลัก

  • ทำงานในโหมด Strict Mode โดยอัตโนมัติ
  • แต่ละโมดูลมี Scope ของตัวเอง (ไม่มลัทธตัวแปร Global)
  • โหลดแบบ Asynchronous (Non-blocking)
  • ต้องรันผ่าน HTTP Server (ไม่ทำงานกับไฟล์ file:// โดยตรง)

ตัวอย่าง: สร้างและใช้งาน Modules

1. ไฟล์ sample.js (Export)

// sample.js
let resultEle = document.querySelector(".result");

export default function testImport() {
    resultEle.innerHTML = "✅ โมดูล testImport ถูกนำเข้าสำเร็จ";
}

export function tellTime() {
    return new Date().toLocaleTimeString("th-TH");
}

2. ไฟล์ script.js (Import)

// script.js
import testImport from "./sample.js";
import { tellTime } from "./sample.js";

let resultEle = document.querySelector(".result");
document.querySelector(".Btn").addEventListener("click", () => {
    resultEle.innerHTML = testImport() + "<br>";
    resultEle.innerHTML += "เวลาปัจจุบัน: " + tellTime();
});

3. ไฟล์ index.html

<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Modules</title>
    <style>
        body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
        .result { font-size: 18px; font-weight: 500; color: blueviolet; }
        button { padding: 8px 16px; margin: 10px 0; cursor: pointer; }
    </style>
</head>
<body>
    <h1>Modules ใน JavaScript</h1>
    <button class="Btn">IMPORT โมดูล</button>
    <div class="result"></div>
    <h3>กดปุ่มด้านบนเพื่อนำเข้าโมดูล</h3>
    
    <!-- ต้องระบุ type="module" -->
    <script src="script.js" type="module"></script>
</body>
</html>

วิธีรัน (สำคัญ!)

❌ ไม่ได้เปิดไฟล์ HTML โดยตรง (double-click)
✅ ต้องรันผ่าน Local Server เช่น:

  • VS Code: Live Server Extension (คลิกขวา → Open with Live Server)
  • Node.js: npx serve หรือ python -m http.server
  • Vite: npm create vite@latest (แนะนำสำหรับโปรเจกต์ใหม่)

ประเภทของ Export/Import

Named Exports (หลายตัวต่อไฟล์)

// export
export const PI = 3.14159;
export function add(a, b) { return a + b; }
export class User { }

// import
import { PI, add, User } from "./math.js";
import { add as addNumbers } from "./math.js"; // เปลี่ยนชื่อ

Default Export (เพียง 1 ต่อไฟล์)

// export
export default function() { return "default"; }
// หรือ
const obj = { name: "Test" };
export default obj;

// import (ตั้งชื่อได้เอง)
import myDefault from "./module.js";
import anything from "./module.js";

รวมทั้งสองแบบ

import MyDefault, { named1, named2 } from "./module.js";

Dynamic Import (นำเข้าแบบไดนามิก)

// ใช้ได้ในฟังก์ชันทั่วไป ไม่ต้องอยู่ระดับบนสุด
async function loadModule() {
    const module = await import("./sample.js");
    module.testImport();
}

// ใช้สำหรับ Code Splitting / Lazy Loading
button.addEventListener("click", () => {
    import("./heavy-module.js").then(module => {
        module.doHeavyWork();
    });
});