如何使用npm命令编译打字稿?

Lij*_*raj 12 node.js npm typescript

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

npm start
Run Code Online (Sandbox Code Playgroud)

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

node filename
Run Code Online (Sandbox Code Playgroud)

看到输出.

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

node filename
Run Code Online (Sandbox Code Playgroud)

命令

Tho*_*aud 25

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

这是一个想法:

  • 使用tsconfig.json文件配置typescript
  • 运行tsc --watch,所以每次更改.ts文件时,tsc都会编译并生成输出(假设你配置了typescript将输出放在./dist文件夹中)
  • 使用nodemon看,如果在文件中./dist已经改变,如果需要的话重新发起服务器.

以下是一些package.json可以帮助您完成的脚本(要放入)(您需要安装以下模块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'"
}
Run Code Online (Sandbox Code Playgroud)

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

  • 这对我不起作用,因为`nodemon`试图在`watch:build`任务完成之前启动服务器.我从nodemon那里得到一个错误:`找不到模块'.../dist/index.js` (6认同)
  • 您可能需要将nodemon、npm-run-all和rimraf添加到packages.json `npm i rimraf npm-run-all nodemon --save-dev` (2认同)
  • `tsc` 是打字稿编译器。当您使用“npm install typescript”安装 typescript 时,它就会出现。您还可以将其与“npx tsc”一起使用。您可以在[此处](https://www.typescriptlang.org/docs/handbook/compiler-options.html)找到更多信息 (2认同)

Gh1*_*111 8

这是我的方法,假设您将所有typescript文件保存在src文件夹中,并希望在文件夹javascript中生成输出文件./dist。

{
    "name": "yourProjectName",
    "version": "1.0.0",
    "description": "",
    "main": "./dist/index",
    "types": "./dist/index",
    "scripts": {
        "dev": "tsc --watch & nodemon dist"
    },
    "author": "Gh111",
    "license": "ISC",
    "devDependencies": {
        "yourdevDependencies": "^1.0.0"
    }
}
Run Code Online (Sandbox Code Playgroud)

和打字稿配置文件 tsconfig.json

{
  "compilerOptions": {
    "target": "es5",       
    "module": "commonjs",  
    "outDir": "./dist",    
  },
  "include": ["./src/**/*"],
  "exclude": [
    "node_modules"
  ]
}
Run Code Online (Sandbox Code Playgroud)

好的,这是怎么回事

首先,我们应该创建tsconfig.json并告诉打字稿将编译后的文件放入./dist文件夹中,同时我们应该排除node_module文件夹或我们想要的任何内容,并包含["./src/**/*"]目录中的所有内容。

在packages.json文件中之后,我们应该指定编译index.js文件的路径

"main": "./dist/index"

最后我们告诉tsc给--watch任何typescript变化,nodemon内部看./dist目录,如果有新的变化nodemon将重新启动服务器。

"scripts": {
    "dev": "tsc --watch & nodemon dist"
 },
Run Code Online (Sandbox Code Playgroud)

运行脚本类型 npm run dev


dem*_*isx 7

这基于@ThomasThiebaud提出的解决方案。我必须对其稍加修改,以确保dist/在nodemon尝试启动服务器之前已内置文件。

"scripts": {
    "clean": "rimraf dist",
    "build": "tsc",
    "watch:build": "tsc --watch",
    "watch:server": "nodemon './dist/index.js' --watch './dist'",
    "start": "npm-run-all clean build --parallel watch:build watch:server --print-label"
  },
Run Code Online (Sandbox Code Playgroud)

您仍然需要运行npm start以开始整个过程​​。