รัน Typescript ผ่าน Node ตรงๆด้วย ts-node

ปกติแล้ว Node.js นั้นจะทำการ execute JavaScript เท่านั้น ซึ่งถ้า Developer นั้นอยากเขียน Project ด้วย TypeScript ก็จะต้องทำการ compile จาก .ts ให้เป็น .js ก่อน

พอดีเห็น GitHub มีโปรเจคหน้าสนใจชื่อว่า ts-node ซึ่งทำให้เราสามารถรัน .ts ไฟล์ได้ตรงๆเลยครับ
Link: https://github.com/TypeStrong/ts-node

การใช้งานก็คือรัน commandline นี้เพื่อทำการรัน Node

ts-node main.ts

มาลุยกันครับ

เริ่มจากเรามี TypeScript file (.ts) ที่สั่งสร้าง http server ชื่อ main.ts

import * as http from "http";

class HttpServer {
private server : http.Server;
public start(){
this.server = http.createServer( (request, response) => {
response.write('Hello...!');
response.end();
});

this.server.listen(8080);
console.log("start server...");
}

public stop(){
this.server.close(()=>{}
);
}
}

let serv = new HttpServer();
serv.start();

ทีนี้เราก็ลอง install ts-node ก่อนครับ

npm install ts-node

เรามาลองรันกันดูครับ

ts-node main.ts

เวิร์คดี!!

runable.png

ถ้าเรามาลองดู Process Tree เราก็จะพบว่าจริงๆแล้วตัว ts-node นั้นก็ทำการรัน node process และทำการรัน bin.js ซึ่งเป็น code ของ ts-node เพื่อให้มันสามารถรัน main.ts ได้

process_tree.png

สรุปแล้วผมคิดว่าโปรเจคนี้น่าสนใจนะครับ เพราะช่วยลดขั้นตอนการ compile ไป JavaScript ไป 🙂
ทั้งนี้ทั้งนั้นต้องทดสอบว่าถ้าเป็นโปรเจคที่ซับซ้อนจะเป็นยังไงบ้าง…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s