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"]
// 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));
// 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);
// index.ts
export { add, multiply } from "./math";
export { default as Course } from "./Course";
{
"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 ช่วยให้ TypeScript ตรวจเข้มขึ้น เช่น
strictNullChecksnoImplicitAnystrictFunctionTypesแนะนำเปิด strict: true สำหรับ project ใหม่
{
"compilerOptions": {
"baseUrl": "src",
"paths": {
"@/*": ["*"],
"@/services/*": ["services/*"]
}
}
}
ตัวอย่าง import:
import { UserService } from "@/services/UserService";
โดยที่ saved คือจำนวน import path ที่ลดลง, directImports คือจำนวน import โดยตรงหลายไฟล์, และ barrelImports คือจำนวน import ผ่านไฟล์รวม เช่น index.ts
target ใน tsconfig กำหนดอะไรstrictNullChecks ช่วยป้องกันปัญหาใด