How to run TypeScript files from command line?

前端 未结 13 1405
死守一世寂寞
死守一世寂寞 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:33

    Like Zeeshan Ahmad's answer, I also think ts-node is the way to go. I would also add a shebang and make it executable, so you can just run it directly.

    1. Install typescript and ts-node globally:

      npm install -g ts-node typescript
      

      or

      yarn global add ts-node typescript
      
    2. Create a file hello with this content:

      #!/usr/bin/env ts-node-script
      
      import * as os from 'os'
      
      function hello(name: string) {
          return 'Hello, ' + name
      }
      const user = os.userInfo().username
      console.log(`Result: ${hello(user)}`)
      

      As you can see, line one has the shebang for ts-node

    3. Run directly by just executing the file

      $ ./hello
      Result: Hello, root
      

    Some notes:

    • This does not seem to work with ES modules, as Dan Dascalescu has pointed out.
    • See this issue discussing the best way to make a command line script with package linking, provided by Kaspar Etter. I have improved the shebang accordingly

    Update 2020-04-06: Some changes after great input in the comments: Update shebang to use ts-node-script instead of ts-node, link to issues in ts-node.

    0 讨论(0)
  • 2020-11-27 10:35

    To add to @Aamod answer above, If you want to use one command line to compile and run your code, you can use the following:

    Windows:

    tsc main.ts | node main.js
    

    Linux / macOS:

    tsc main.ts && node main.js
    
    0 讨论(0)
  • 2020-11-27 10:37

    This question was posted in 2015. In 2018, node recognizes both .js and .ts. So, running node file.ts will also run.

    0 讨论(0)
  • 2020-11-27 10:40

    For environments such as Webstorm where the node command cannot be changed to ts-node or npx:

    1. npm install ts-node typescript (Install dependencies)
    2. node --require ts-node/register src/foo.ts (Add --require ts-node/register to "Node parameters")
    0 讨论(0)
  • 2020-11-27 10:42

    Just helpful information - here is newest TypeScript / JavaScript runtime Deno.

    It was created by the creator of node Ryan Dahl, based on what he would do differently if he could start fresh.

    0 讨论(0)
  • 2020-11-27 10:44
    1. Install ts-node node module globally.
    2. Create node runtime configuration (for IDE) or use node in command line to run below file js file (The path is for windows, but you can do it for linux as well) ~\AppData\Roaming\npm\node_modules\ts-node\dist\bin.js
    3. Give your ts file path as a command line argument.
    4. Run Or Debug as you like.
    0 讨论(0)
提交回复
热议问题