如何使用 npm 命令编译打字稿? [英] How to compile typescript using npm command?

查看:70
本文介绍了如何使用 npm 命令编译打字稿?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我只是想知道是否有任何命令可以直接编译打字稿代码并获得输出.现在,我正在做的是,每次我在文件中进行更改时,我都必须重新运行命令才能编译它

Well I just wanted to know is there any command which will directly compile the typescript code and get the output. Right now, what i am doing is,every time when i make changes in the file i have to re run the command inorder to compile it

npm start

这将启动浏览器,然后我必须使用 ctrl + c 停止执行,然后我必须使用 npm 命令运行该文件

This starts the browser and then i have to stop the execution using ctrl + c and then i have to run the file using the npm command

node filename

查看输出.

所以我想知道的是,是否有任何 npm 命令可以编译 .ts 文件并查看我在使用

So what i want to know is, is there any npm command which will compile the .ts file and see the changes which i have made in the file while i run the file using the

node filename

命令

推荐答案

您可以使用 --watch 参数启动 tsc 命令(打字稿编译器).

You can launch the tsc command (typescript compiler) with --watch argument.

这是一个想法:

  • 使用 tsconfig.json 文件配置打字稿
  • 运行 tsc --watch,所以每次你改变一个 .ts 文件时,tsc 都会编译它并产生输出(让假设您配置打字稿将输出放在 ./dist 文件夹中)
  • 使用 nodemon 观察 ./dist 中的文件是否已更改,以及是否需要重新启动服务器.
  • Configure typescript using tsconfig.json file
  • Run tsc --watch, so every time you change a .ts file, tsc will compile it and produce the output (let say you configured typescript to put the output in ./dist folder)
  • Use nodemon to watch if files in ./dist have changed and if needed to relaunch the server.

这里有一些脚本(放在 package.json 中)可以帮助你做到这一点(你需要安装以下模块 npm install --save typescript nodemon npm-运行所有 rimraf)

Here are some scripts (to put in package.json) that can help you to do it (you will need to install the following modules npm install --save typescript nodemon npm-run-all rimraf)

"scripts": {
    "clean": "rimraf dist",
    "start": "npm-run-all clean --parallel watch:build watch:server --print-label",
    "watch:build": "tsc --watch",
    "watch:server": "nodemon './dist/index.js' --watch './dist'"
}

然后你只需要在终端中运行 npm start

Then you just need to run npm start in a terminal

这篇关于如何使用 npm 命令编译打字稿?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆