Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile typescript code from STDIN rather than a file?

Tags:

typescript

I'm building a (simple) command line tool that writes a temporary typescript file to disk and then performs type checking on the file via tsc /tmp/foo/bar.ts --noEmit.

I would like to send the code to tsc via STDIN instead of writing a file in /tmp.

How can I run tsc --noEmit on code that is sent to STDIN?

like image 533
Rick Avatar asked Jan 22 '19 17:01

Rick


1 Answers

I tried ts-node as vike suggested. It worked fine but there's about a 1s startup cost to both ts-node and tsc. Creating all the files and compiling (tsc --noEmit *.ts) them all at once allowed me to pay startup cost that only once.

tldr;

I wanted to test the conformance of the 437 ShExJ JSON tests against @types/shexj. I cloned the tests and constructed trivial ts files that tested the type.

for f in *.json; do time (
  (
    echo -en "import {Schema} from 'shexj'\nconst x:Schema = " &&
    cat $f
  ) |
  ../node_modules/.bin/ts-node
); done

real    0m1,336s
user    0m2,919s
sys     0m0,121s

real    0m1,233s
user    0m2,586s
sys     0m0,101s

real    0m1,374s
user    0m2,979s
sys     0m0,127s

real    0m1,257s
user    0m2,692s
sys     0m0,096s
…

It was taking > 1.2s/file. I bypassed ts-node and went straight to tsc:

for f in *.json; do time (
  (
    echo -en "import {Schema} from 'shexj'\nconst x:Schema = " &&
    cat $f
  ) > ../ts/$f.ts &&
  tsc --noEmit ../ts/$f.ts
); done

real    0m2,909s
user    0m7,356s
sys     0m0,171s

real    0m2,735s
user    0m7,077s
sys     0m0,182s

real    0m2,669s
user    0m6,822s
sys     0m0,173s

real    0m2,670s
user    0m6,952s
sys     0m0,123s
…

This was taking > 2.6s/file. As slow was invoking ts-node individually was, it was still faster than invoking tsc individually. (I wonder how they managed that.)

I wrote them all out at once:

time (
  for f in 0*.json; do (
    echo -en "import {Schema} from 'shexj'\nconst x:Schema = " &&
    cat $f
  ) > ../ts/$f.ts;
  done
)

real    0m0,021s
user    0m0,013s
sys     0m0,009s

and compiled them at once:

time tsc --noEmit ../ts/*.ts

real    0m3,198s
user    0m8,424s
sys     0m0,148s

Extrapolating, this saved me 9.5 mins of full CPU.

like image 86
ericP Avatar answered Dec 06 '22 03:12

ericP