无需``ts-node''即可直接使用``'node''来直接运行打字稿代码,为什么起作用?
我已经设置了一个非常简单的node.js项目,其中包含打字稿。 的软件包
{
"name": "mydemo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"lint": "eslint . --fix",
"test": "echo \"Error: no test specified\" && exit 1",
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/node-fetch": "^2.6.1",
"@typescript-eslint/eslint-plugin": "^5.23.0",
"@typescript-eslint/parser": "^5.23.0",
"eslint": "^8.15.0",
"node-fetch": "^3.2.4",
"ts-node": "^10.7.0",
"typescript": "^4.6.4"
}
}
我
。 。
src/main.ts :
const sayHi = () => {
console.log('HI!12345');
}
sayHi();
我的tsconfig.json
:
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"outDir": "dist",
"sourceMap":true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}
}
使用上述设置,我可以在终端上运行node src/main.ts
。每当我在main.ts
中更新代码时,我直接运行node src/main.ts
还显示了带有最新代码的结果。
我本可以安装ts节点
,我尝试过,并且也有效。但是我想知道为什么没有ts节点
我的设置工作正常。我的意思是我已经可以通过node
命令运行打字稿代码,而无需编译和运行JS。
有人可以向我解释吗?似乎根本不需要ts节点
。
I have set up a very simple node.js project with TypeScript. My package.json, from which you can see what packages I have installed (there is no ts-node
), looks like this:
{
"name": "mydemo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"lint": "eslint . --fix",
"test": "echo \"Error: no test specified\" && exit 1",
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/node-fetch": "^2.6.1",
"@typescript-eslint/eslint-plugin": "^5.23.0",
"@typescript-eslint/parser": "^5.23.0",
"eslint": "^8.15.0",
"node-fetch": "^3.2.4",
"ts-node": "^10.7.0",
"typescript": "^4.6.4"
}
}
Project structure:
The src/main.ts
:
const sayHi = () => {
console.log('HI!12345');
}
sayHi();
My tsconfig.json
:
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"outDir": "dist",
"sourceMap":true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}
}
With the above setup, I can run node src/main.ts
on terminal. Whenever I update code in main.ts
I directly run node src/main.ts
also shows the result with latest code.
I could have installed ts-node
, I tried and it works as well. But I wonder why without ts-node
my setup works just fine. I mean I can already run TypeScript code by node
command without the need to compile to and run JS.
Could someone please explain to me? Seems ts-node
is not needed at all.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
打字稿语法是JavaScript的超集。您的代码不使用任何特定于特定于字样的语法(例如类型声明或类型注释),因此它也是有效的JS文件,plain
node
可以执行该文件。如果添加了一些类型的注释,您将获得node
的错误:TypeScript syntax is a superset of JavaScript. Your code does not use any TypeScript specific syntax (like type declarations or type annotations), so it's also a valid JS file, which plain
node
can execute. If you add some type annotations, you'll get an error withnode
: