หัวข้อ 6: Module System import/export และการตั้งค่า tsconfig

คำจำกัดความ

Module System คือวิธีแยกโค้ดเป็นหลายไฟล์แล้วนำกลับมาใช้ร่วมกันด้วย import และ export ส่วน tsconfig.json คือไฟล์กำหนดค่าการ compile TypeScript

%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#458588", "primaryTextColor": "#fbf1c7", "primaryBorderColor": "#fabd2f", "lineColor": "#a89984", "secondaryColor": "#b8bb26", "tertiaryColor": "#d3869b", "background": "#282828", "mainBkg": "#3c3836", "textColor": "#ebdbb2"}}}%%
flowchart LR
  A["module-a.ts
export"] --> C["app.ts
import"] B["module-b.ts
default export"] --> C C --> D["tsc
TypeScript Compiler"] D --> E["dist
JavaScript Output"]

Named Export

// math.ts
export const add = (a: number, b: number): number => {
  // คืนค่าผลบวก
  return a + b;
};

export const multiply = (a: number, b: number): number => {
  return a * b;
};
// app.ts
import { add, multiply } from "./math";

console.log(add(2, 3));
console.log(multiply(4, 5));

Default Export

// Course.ts
export default class Course {
  constructor(public title: string) {}
}
// app.ts
import Course from "./Course";

const course = new Course("Web Programming");
console.log(course.title);

Re-export

// index.ts
export { add, multiply } from "./math";
export { default as Course } from "./Course";

tsconfig.json

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "strict": true,
    "rootDir": "src",
    "outDir": "dist"
  }
}
Option ความหมาย
target เวอร์ชัน JavaScript ที่ compile ออกมา
module รูปแบบ module
strict เปิดชุดตรวจ type เข้มงวด
rootDir โฟลเดอร์ source
outDir โฟลเดอร์ output

strict mode

strict mode ช่วยให้ TypeScript ตรวจเข้มขึ้น เช่น

แนะนำเปิด strict: true สำหรับ project ใหม่

Path Alias

{
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
      "@/*": ["*"],
      "@/services/*": ["services/*"]
    }
  }
}

ตัวอย่าง import:

import { UserService } from "@/services/UserService";

สมการจำนวน Import ที่ลดลงด้วย Barrel File

saved = directImports - barrelImports

โดยที่ saved คือจำนวน import path ที่ลดลง, directImports คือจำนวน import โดยตรงหลายไฟล์, และ barrelImports คือจำนวน import ผ่านไฟล์รวม เช่น index.ts

แบบทดสอบหลังเรียน

  1. Named Export และ Default Export ต่างกันอย่างไร
  2. Re-export ใช้ทำอะไร
  3. target ใน tsconfig กำหนดอะไร
  4. strictNullChecks ช่วยป้องกันปัญหาใด
  5. Path Alias มีประโยชน์อย่างไร

กลับสัปดาห์ที่ 6