node.js 如何从命令行运行 TypeScript 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33535879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to run TypeScript files from command line?
提问by Gunchars
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 coffee hello.coffeeand ES6 has babel-node hello.js. How do I do the same with Typescript?
我很难找到这个问题的答案。与普通的Node.js,你可以运行任何js文件node path/to/file.js,用CoffeeScript的是coffee hello.coffee和ES6了babel-node hello.js。我如何用 Typescript 做同样的事情?
My project has a tsconfig.jsonwhich is used by Webpack/ts-loader to build a nice little bundle for the browser. I have a need for a build step run from the console before that, though, that would use some of the .tsfiles used in the project to generate a schema, but I can't seem to be able to run a single Typescript file without compiling the whole project.
我的项目有一个tsconfig.jsonWebpack/ts-loader 使用它为浏览器构建一个漂亮的小包。在此之前,我需要从控制台运行一个构建步骤,这将使用.ts项目中使用的一些文件来生成架构,但我似乎无法在不编译的情况下运行单个 Typescript 文件整个项目。
回答by basarat
How do I do the same with Typescript
我如何用 Typescript 做同样的事情
You can leave tscrunning in watch mode using tsc -w -p .and it will generate .jsfiles for you in a live fashion, so you can run node foo.jslike normal
您可以tsc使用监视模式保持运行,tsc -w -p .它会.js以实时方式为您生成文件,因此您可以node foo.js正常运行
TS Node
TS节点
There is ts-node : https://github.com/TypeStrong/ts-nodethat will compile the code on the fly and run it through node
有 ts-node :https: //github.com/TypeStrong/ts-node将动态编译代码并通过节点运行它
npx ts-node src/foo.ts
回答by Aamod Tiwari
We have following steps
我们有以下步骤
First you need to install typescript
npm install -g typescript
首先你需要安装打字稿
npm install -g 打字稿
2.Create one file helloworld.ts
2.创建一个文件helloworld.ts
function hello(person){
return "Hello, " + person;
}
let user = "Aamod Tiwari";
const result = hello(user);
console.log("Result",result)
3. Open command prompt and type the following command
3.打开命令提示符并键入以下命令
tsc helloworld.ts
tsc helloworld.ts
- Again run the command
- 再次运行命令
node helloworld.js
节点 helloworld.js
- Result will display on console
- 结果将显示在控制台上
回答by tony2tones
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:
要添加到上面的@Aamod 答案中,如果您想使用一个命令行来编译和运行您的代码,您可以使用以下命令:
Windows:
视窗:
tsc main.ts | node main.js
Linux / macOS:
Linux / macOS:
tsc main.ts && node main.js
回答by Zeeshan Ahmad
Run the below commands and install the required packages globally:
运行以下命令并全局安装所需的包:
npm install -g ts-node
npm install -g typescript
Now run the following command to execute a typescript file:
现在运行以下命令来执行打字稿文件:
ts-node typescript-file.ts
回答by Joyer
Write yourself a simple bash wrapper may helps.
为自己编写一个简单的 bash 包装器可能会有所帮助。
#!/bin/bash
npx tsc && node ${1%%.ts}
回答by Alexander Emelianov
回答by Kariem
Like Zeeshan Ahmad's answer, I also think ts-nodeis the way to go. I would also add a shebang and make it executable, so you can just run it directly.
就像Zeeshan Ahmad 的回答一样,我也认为ts-node是要走的路。我还会添加一个shebang并使其可执行,因此您可以直接运行它。
Install typescript and ts-node globally:
npm install -g ts-node typescriptor
yarn global add ts-node typescriptCreate a file
hellowith 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
Run directly by just executing the file
$ ./hello Result: Hello, root
全局安装 typescript 和 ts-node:
npm install -g ts-node typescript或者
yarn global add ts-node typescript创建一个
hello包含以下内容的文件:#!/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)}`)如您所见,第一行有 ts-node 的shebang
直接执行文件就可以运行
$ ./hello Result: Hello, root
Some notes:
一些注意事项:
- This does not seem to work with ES modules, as Dan Dascalescu has pointed out.
- See this issuediscussing the best way to make a command line script with package linking, provided by Kaspar Etter. I have improved the shebang accordingly
- 正如Dan Dascalescu 指出的那样,这似乎不适用于 ES 模块。
- 请参阅此问题,讨论制作带有包链接的命令行脚本的最佳方法,由 Kaspar Etter 提供。我相应地改进了shebang
Update 2020-04-06: Some changes after great input in the comments: Update shebang to use ts-node-scriptinstead of ts-node, link to issues in ts-node.
2020 年 4 月 6 日更新:在评论中大量输入后的一些更改:更新 shebang 以使用ts-node-script而不是ts-node,链接到 ts-node 中的问题。
回答by Dan Dascalescu
None of the other answers discuss how to run a TypeScript script that uses modules, and especially modern ES Modules.
其他答案都没有讨论如何运行使用模块的 TypeScript 脚本,尤其是现代 ES 模块。
First off, ts-node doesn't workin that scenario, as of March 2020. So we'll settle for tscfollowed by node.
首先,截至 2020 年 3 月,ts-node在这种情况下不起作用。所以我们将满足tsc于node.
Second, TypeScript still can't output .mjsfiles. So we'll settle for .jsfiles and "type": "module"in package.json.
其次,TypeScript 还是不能输出.mjs文件。因此,我们会满足于.js文件和"type": "module"在package.json。
Third, you want clean importlines, without specifying the .jsextension (which would be confusing in .tsfiles):
第三,您需要干净的import线条,而不指定.js扩展名(这会在.ts文件中造成混淆):
import { Lib } from './Lib';
Well, that's non-trivial. Node requiresspecifying extensions on imports, unless you use the experimental-specifier-resolution=nodeflag. In this case, it would enable Node to look for Lib.jsor Lib/index.jswhen you only specify ./Libon the importline.
嗯,这很重要。除非您使用该标志,否则Node需要在导入时指定扩展名experimental-specifier-resolution=node。在这种情况下,它将使 Node 能够查找Lib.js或Lib/index.js仅当您指定时./Lib就import行了。
Fourth, there's still a snag: if you have a different mainfilename than index.jsin your package, Node won't find it.
第四,还有一个问题:如果您的main文件名与index.js包中的文件名不同,Node 将找不到它。
Transpiling makes things a lot messier than running vanilla Node.
与运行普通 Node.js 相比,转译使事情变得更加混乱。
Here's a sample repo with a modern TypeScript project structure, generating ES Module code.
这是一个具有现代 TypeScript 项目结构的示例存储库,生成 ES 模块代码。
回答by Paramvir Singh Karwal
- Install
ts-nodenode module globally. - Create node runtime configuration (for IDE) or use
nodein command line to run below filejsfile (The path is for windows, but you can do it for linux as well)~\AppData\Roaming\npm\node_modules\ts-node\dist\bin.js - Give your
tsfile path as a command line argument. - Run Or Debug as you like.
ts-node全局安装节点模块。- 创建节点运行时配置(用于 IDE)或
node在命令行中使用以在文件js文件下运行(路径适用于 windows,但您也可以为 linux 执行)~\AppData\Roaming\npm\node_modules\ts-node\dist\bin.js - 将您的
ts文件路径作为命令行参数。 - 根据需要运行或调试。
回答by Harlin
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.
以防万一有人像我一样疯了,想像运行 .js 脚本一样运行 typescript 脚本,你可以试试这个。我写了一个看起来使用 node 执行 .ts 脚本的hacky脚本。
#!/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= # 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:
您可以这样做或编写自己的,但本质上,它会创建 .js 文件,然后使用 node 运行它,如下所示:
# 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.
简单的。只要确保您的脚本只有一个“。” 否则,您需要以不同于我所展示的方式更改您的 JSFILE。

