TypeScript modules (ESM)



export / import

// math.ts
export function add(a: number, b: number): number {
  return a + b;
}

export const PI = 3.14159;

export interface Point {
  x: number;
  y: number;
}

export class Vector {
  constructor(public x: number, public y: number) {}
}
// main.ts
import { add, PI, type Point, Vector } from "./math.js";

add(1, 2);
const p: Point = { x: 1, y: 2 };
new Vector(3, 4);

หมายเหตุ extension: ในโปรเจกต์ Node ESM ("module": "NodeNext") ต้องเขียน ./math.js (นามสกุลของ output) แม้ไฟล์จริงเป็น .ts — ในโปรเจกต์ที่ใช้ bundler ("module": "bundler") ไม่ต้องมีนามสกุล

default export

// logger.ts
export default class Logger {
  log(msg: string) {
    console.log(`[LOG] ${msg}`);
  }
}
// main.ts
import Logger from "./logger.js";       // ไม่มี { } — ชื่ออะไรก็ได้
import MyLogger from "./logger.js";     // ก็ได้

named export นิยมกว่า default ในทีมส่วนใหญ่ — refactor/rename ง่ายกว่า, autocomplete ดีกว่า, ไม่มีการตั้งชื่อสองแบบ

export หลายวิธี

// re-export
export { add, subtract } from "./math.js";
export * from "./utils.js";
export { default as Logger } from "./logger.js";

// export ท้ายไฟล์
function helper() {}
const config = {};
export { helper, config };

// rename ตอน export / import
export { internalName as publicName };
import { publicName as localName } from "./mod.js";

import type / export type

import type = “import สิ่งนี้เพื่อใช้เป็น type เท่านั้น” — ถูกลบทั้งหมดตอน compile (ไม่มีใน JS output):

import type { User } from "./types.js";        // type-only — หายตอน compile
import { fetchUser } from "./api.js";          // value — อยู่ใน output

// ผสมในบรรทัดเดียว
import { fetchUser, type User, type Config } from "./api.js";

ทำไมสำคัญ:

  • ป้องกัน circular dependency (type ไม่ทำให้เกิด runtime cycle)
  • bundler ตัด import ที่ไม่จำเป็นออกได้แม่นขึ้น
  • ตั้ง "verbatimModuleSyntax": true — บังคับให้ type-only import เขียน type ชัด ๆ (แนะนำ)
// verbatimModuleSyntax = true
import { User } from "./types.js";     // Error ถ้า User เป็น type เท่านั้น
import type { User } from "./types.js"; // ต้องเขียนแบบนี้

module resolution

tsconfig "moduleResolution":

ค่าใช้เมื่อ
"bundler"โปรเจกต์ที่ใช้ Vite/esbuild/webpack — ไม่ต้องนามสกุล, รองรับ exports field
"NodeNext"โปรเจกต์ Node ที่รันด้วย node ตรง ๆ — ต้องนามสกุล .js
"Node10" (เดิม "Node")legacy CJS — เลี่ยง

path alias — เลิก ../../../

// tsconfig.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"],
      "@config": ["src/config/index.ts"]
    }
  }
}
// แทน  import { db } from "../../../config/database.js";
import { db } from "@/config/database.js";
import config from "@config";

ระวัง: tsc เข้าใจ paths แต่ ไม่ rewrite path ตอน compile — runtime ต้องมี tool ที่รู้จัก alias ด้วย:

  • Vite/esbuild/webpack — ตั้ง alias ใน config ของมันด้วย
  • Node — ใช้ tsconfig-paths หรือ imports field ใน package.json ("#config")
  • tsx — อ่าน tsconfig paths ให้

ambient module (สำหรับไฟล์ที่ไม่มี type)

// types/images.d.ts
declare module "*.png" {
  const src: string;
  export default src;
}
import logo from "./logo.png";   // logo: string

(บทที่ 32 ว่าด้วย declaration file)

side-effect import

import "./polyfills.js";        // รันไฟล์ ไม่ import อะไร
import "./styles.css";          // ใน bundler

dynamic import

async function loadHeavyModule() {
  const { processLargeData } = await import("./heavy.js");   // โหลดตอนต้องใช้
  return processLargeData;
}

// type ยังถูก — import() คืน Promise<typeof module>

เรื่องที่คนมักพลาด

  • ลืมนามสกุล .js ใน "module": "NodeNext" — import from "./math" error; ต้อง "./math.js"
  • default export แล้ว rename กระจาย — import Foo ในไฟล์นึ่ง import Bar ในอีกไฟล์ — สับสน; ใช้ named
  • import { User } เมื่อ User เป็น type โดยไม่มี type — เพิ่ม runtime import ที่ไม่จำเป็น; ตั้ง verbatimModuleSyntax
  • paths alias แต่ runtime ไม่รู้จัก — tsc ไม่ rewrite; ตั้ง alias ใน bundler / ใช้ tsconfig-paths / imports field
  • export default object literal แล้ว circular import — value cycle; แยก type ด้วย import type
  • import * as X แล้วเรียก X() — namespace import ไม่ใช่ function; ใช้ named
  • ปน CommonJS (require) กับ ESM (import) ในไฟล์เดียว — เลือกอย่างเดียว

สรุป

  • ESM: export function/export const/export { } และ import { name } from "./mod.js"
  • named export นิยมกว่า default (refactor/autocomplete ดีกว่า)
  • import type { T } — type-only, หายตอน compile (กัน circular dep); verbatimModuleSyntax บังคับให้ชัด
  • "moduleResolution": "bundler" (Vite) หรือ "NodeNext" (Node — ต้องนามสกุล .js)
  • path alias "@/*": ["src/*"] — tsc เข้าใจแต่ไม่ rewrite; runtime ต้องมี tool รู้จักด้วย
  • await import(...) — dynamic import (code splitting), type ยังถูก

บทถัดไปว่าด้วย type guard และ exhaustiveness — user-defined type guard x is T, assertion function และ never