How to run TypeScript files from command line?

前端 未结 13 1495
死守一世寂寞
死守一世寂寞 2020-11-27 10:13

I\'m having a surprisingly hard time finding an answer to this. With plain Node.JS, you can run any js file with node path/to/file.js, with CoffeeScript it\'s <

13条回答
  •  青春惊慌失措
    2020-11-27 10:23

    Just in case anyone is insane like me and wants to just run typescript script as though it was a .js script, you can try this. I've written a hacky script that appears to execute the .ts script using node.

    #!/usr/bin/env bash
    
    NODEPATH="$HOME/.nvm/versions/node/v8.11.3/bin" # set path to your node/tsc
    
    export TSC="$NODEPATH/tsc"
    export NODE="$NODEPATH/node"
    
    TSCFILE=$1 # only parameter is the name of the ts file you created.
    
    function show_usage() {
        echo "ts2node [ts file]"
        exit 0
    }
    
    if [ "$TSCFILE" == "" ]
    then
        show_usage;
    fi
    
    JSFILE="$(echo $TSCFILE|cut -d"." -f 1).js"
    
    $TSC $TSCFILE && $NODE $JSFILE
    

    You can do this or write your own but essentially, it creates the .js file and then uses node to run it like so:

    # tsrun myscript.ts
    

    Simple. Just make sure your script only has one "." else you'll need to change your JSFILE in a different way than what I've shown.

提交回复
热议问题