Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any option to compile and run a ts code faster using tsc or ts-node or anything else?

Currently we have client server application (for competitive coding purposes) where client hit compile and run and sends ts code to server where ts code is stored in a file and run locally with testcases on server and output is returned to client with test case pass/fail result. But running ts file is very slow and this is taking so much time.

I am using ts-node in transpileonly mode to compile and run the file locally in server.

eg. npx ts-node -T tsFileName.ts

Our requirement is fastened to compile and run time of ts code.

like image 442
Manoj Singh Avatar asked Dec 01 '22 09:12

Manoj Singh


2 Answers

I added these environment variables and startup time went from seconds to, milliseconds probably:

TS_NODE_FILES=true TS_NODE_TRANSPILE_ONLY=true ts-node ./script.ts

Consider installing ts-node via [sudo] npm install -g typescript ts-node, then you avoid the extra steps that npx takes to make sure ts-node is installed every time.

Edit: I have since switched to Sucrase via [sudo] npm install -g sucrase. I just replace any ts-node occurrence with sucrase-node to get roughly a 20x speed boost in my testing. It does not need environment variables. It doesn't do any typechecking, it just makes sure you have fast dev iterations. Then you can run full tsc builds with typechecking in your editor and in CI. For my use case that is perfect, but your situation may be different. I was also able to speed up my Jest tests with @sucrase/jest-plugin.

sucrase-node ./script.ts
like image 136
kvz Avatar answered Dec 04 '22 07:12

kvz


TS-Node Official Recommendations

The official TS-Node docs outline several performance recommendations, some of which others have commented on.

https://typestrong.org/ts-node/docs/performance/

However, I'm surprised no one has mentioned the SWC integration! From the docs:

Use our swc integration. This is by far the fastest option

Speedy Web Compiler (SWC)

SWC, or Speedy Web Compiler, is a transpiler for JavaScript/TypeScript written completely in Rust. As such, it's much faster than anything you're going to get out of alternatives like tsc or babel.

According to the SWC website (https://swc.rs/):

SWC is 20x faster than Babel on a single thread and 70x faster on four cores.

Set up with TS-Node

Add the SWC core library to your project:

npm i -D @swc/core

And add the following to your tsconfig.json:

{
  "ts-node": {
    "swc": true
  }
}

And you're good to go! Enjoy blazingly fast transpiling.

like image 21
Steve DeWald Avatar answered Dec 04 '22 06:12

Steve DeWald