Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compile typescript using npm command?

I just wanted to know is there any command which will directly compile the typescript code and get the output. Right now, what I am doing is, every time when I make changes in the file I have to re-run the command in order to compile it

npm start 

This starts the browser and then I have to stop the execution using Ctrl+C and then I have to run the file using the npm command

node filename 

to see the output.

So what I want to know is, is there any npm command which will compile the .ts file and see the changes which I have made in the file while I run the file using the

node filename 

command

like image 621
Lijin Durairaj Avatar asked Jan 25 '17 13:01

Lijin Durairaj


People also ask

How do I run a TypeScript using npm?

You can use npm to install TypeScript globally, this means that you can use the tsc command anywhere in your terminal. To do this, run npm install -g typescript . This will install the latest version (currently 4.7). An alternative is to use npx when you have to run tsc for one-off occasions.

Which command is used to compile TypeScript?

As you know, TypeScript files can be compiled using the tsc <file name>. ts command.


2 Answers

You can launch the tsc command (typescript compiler) with --watch argument.

Here is an idea :

  • Configure typescript using tsconfig.json file
  • Run tsc --watch, so every time you change a .ts file, tsc will compile it and produce the output (let say you configured typescript to put the output in ./dist folder)
  • Use nodemon to watch if files in ./dist have changed and if needed to relaunch the server.

Here are some scripts (to put in package.json) that can help you to do it (you will need to install the following modules npm install --save typescript nodemon npm-run-all rimraf)

"scripts": {     "clean": "rimraf dist",     "start": "npm-run-all clean --parallel watch:build watch:server --print-label",     "watch:build": "tsc --watch",     "watch:server": "nodemon './dist/index.js' --watch './dist'" } 

Then you just need to run npm start in a terminal

like image 76
ThomasThiebaud Avatar answered Sep 20 '22 15:09

ThomasThiebaud


This is based on solution proposed by @ThomasThiebaud. I had to modify it a little to make sure the files are built in dist/ before nodemon tries to start the server.

"scripts": {     "clean": "rimraf dist",     "build": "tsc",     "watch:build": "tsc --watch",     "watch:server": "nodemon './dist/index.js' --watch './dist'",     "start": "npm-run-all clean build --parallel watch:build watch:server --print-label"   }, 

You still need to run npm start to start the whole thing.

like image 34
demisx Avatar answered Sep 18 '22 15:09

demisx