The Ultimate Guide to ts-node Unlocking TypeScript Execution in Node.js

Introduction to ts-node

ts-node is a TypeScript execution engine for Node.js, enabling developers to seamlessly run TypeScript code without needing a precompilation setup. It acts as a bridge between TypeScript and Node.js, offering a smooth and efficient development experience. This guide explores various APIs provided by ts-node with code snippets to help you leverage its full potential.

Getting Started with ts-node

$ npm install -g ts-node
$ ts-node your-script.ts

Useful APIs and Examples

Register API

Registers TypeScript ahead of node’s executions. It can be utilized in various ways to enhance the development workflow.


require('ts-node').register({
  project: 'tsconfig.custom.json'
});

Register and Compile Files with Custom Settings


require('ts-node').register({
  transpileOnly: true,
  compilerOpts: {
    module: 'CommonJS'
  }
});

Execute ts-node Programmatically


const tsNode = require('ts-node');

tsNode.register({
  transpileOnly: true
});

tsNode.compile('console.log("Running TypeScript with ts-node")');

Using with Node CLI Options


$ node -r ts-node/register app.ts

Execute a TypeScript REPL


$ ts-node

Custom TypeScript Compiler


require('ts-node').register({ 
  compiler: '/path/to/custom-tsc' 
});

Ignore Files or Directories


require('ts-node').register({
  ignore: ['/path/to/ignore', /^regex-pattern-to-ignore/]
});

Example Application

Here’s a simple TypeScript application using ts-node.


// app.ts
import express from 'express';

const app = express();

app.get('/', (req, res) => {
  res.send('Hello from ts-node and TypeScript!');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

To run the application with ts-node, use:

$ ts-node app.ts

Enjoy developing with TypeScript in Node.js using the powerful and convenient capabilities of ts-node.

Hash: 1892370e648850280b5168c5bc4a919ee4ffdfbef34ee3d9548cb44b5ea1874f

Leave a Reply

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