Running Typescript from within Node

To run Typescript in Node, you can either compile the code in advance, or at runtime. Doing this at runtime is convenient, since you probably would be compiling + running the code at the same time every time you run your application.

The easiest way I’ve found to do this is to install ts-node:

npm install ts-node

Then make a small index.js script, which functions as a shim. All the Express.js code can then be moved into a Typescript file.

index.js:

// Fix incompatibility between React 15 and different Webkit versions
delete Object.assign;
Object.assign = require("object.assign").shim();

// Allow Node to read JSX files
require("node-jsx").install({extension: ".jsx"});

// Allow Node to read TS + TSX files
require("ts-node").register();

require("./app.ts")["init"]();

In the app.ts file, you can add all of the regular Express initialization things, as you’d expect, but now you can use types:

function init() {
 const express = require("express");
 const router = express.Router();

 router.use(function (req,res,next) {
    next();
  });
}

export { init as init };

I wrapped the entire thing in a function, which is exported and called by the main index.js script.

Leave a Reply

Your email address will not be published. Required fields are marked *