Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I execute typescript watch and running server at the same time?

I was developing my project in nodejs. I found if I need to code and test api, I will run two console, one is to execute typescript watch, another is to execute server.

I think it's so troublesome. I find other developers on github have written scripts in package.json. It's easy to call any commands. It attracts how to write the scripts and simply my development workflow.

In short, the comand of typescript watch is tsc -w and the comand of running server is node app.js. My idea is merge the commands as tsc -w & node app.js but I can't work the two commands at the same time. How do I do? Thanks.

like image 982
Tony Avatar asked Feb 08 '16 03:02

Tony


People also ask

Can we use TypeScript in server side?

This allows you to write server-side-based applications with strong type checking, which allows you to avoid runtime type errors and other Typescript advantages and take full advantage of Node.

Which command is used to execute the TypeScript code?

We can use the ts-node package to execute TypeScript files from the command line. Install it with npm or other package manager. After that, simply execute the TypeScript files with the command: ts-node filename.

How do I speed up TypeScript compilation?

The first thing that we can consider doing to improve performance, is to skip type checking between other files by setting the isolatedModules compiler option to true . This brings the average compile time down to 9.09 seconds , a 32% reduction in time (not bad for a quick setting change).


2 Answers

TLDR, If you like nodemon this is a straight forward way to get file watch, compilation and execution:

nodemon --ext ts --exec 'tsc && node dist/index.js'

Optionally replace tsc with babel for faster compilation.

Here is a more complete example, in package.json (with source maps):

"scripts": {
  "develop": "nodemon --ext ts --exec 'yarn build --incremental && yarn serve'",
  "build": "tsc",
  "serve": "node --require source-map-support/register dist/index.js",
  ...
},

Install source-map-support as a dependency if you want, ahem... source map support! Otherwise, remove --require source-map-support/register from the serve script above.

tsconfig.json

{
  "compilerOptions": {
    ...
    "sourceMap": true,
    "outDir": "dist",
  }
}
like image 148
Mikael Lirbank Avatar answered Nov 09 '22 05:11

Mikael Lirbank


Step 1

install concurrently, use npm or yarn

yarn add concurrently -D   

Step 2

create a script with this command

"scripts": {
    "run": "tsc && concurrently \"tsc -w\" \"nodemon dist/app.js\"",
}

run tsc first so that your directory has something at the time of running node

And with that you will have running your Typescript application 🚀

like image 35
HerberthObregon Avatar answered Nov 09 '22 06:11

HerberthObregon