Determined not to write boring old JavaScript, I managed to get TypeScript working for the server (haven’t tried the client yet; how hard can it be? )
It’s a very trivial echo service using web sockets… You enter something in the textbox and click send and the server echos it back.
https://rapid-arm.hyperdev.space/
The app bootstrap stuff is untyped (everything is any
), I didn’t want to pull in a big bloated node .d.ts
for so little (but I might stub out the few things I call). In server.ts
it creates an instance of EchoService
from echo.ts
:
// Create echo service
import echo = require('./echo');
var echoService = new echo.EchoService(wss);
Again, wss
is untyped but the important thing is that TypeScript is compiling these and it’s running in node on the server
It’s done using the ts-node
npm package, which you can pass a .ts
file, it compiles on the fly and executes (I presume this is being done in memory based on previous comments that the fs is readyonly, but I haven’t checked).
In package.json, I replaced the start
call to call ts-node
and pass the server:
"start": "node node_modules/ts-node/dist/bin/ts-node.js server.ts"
It’d be nice to have native TypeScript and/or ES classes (I think ES classes will come free with a node upgrade) and editor support, but this’ll do for now!
Note: If playing with the example, you might see “WebSocket closed” and it’ll stop working. Looks like it goes to sleep even though there are open websockets, not sure if that’s intended or not (I hope it’s a bug, otherwise my game prototype won’t work very well!).