Typescript + nodemon + VS Code 与声明合并一起工作

Typescript + nodemon + VS Code to work together with declaration merging

我正在将这个中间件添加到我的 Express 应用程序中

app.use(function(req: express.Request, res: express.Response, next: express.NextFunction) {
    req.rawBody = 'hello2';
    next();
});

并添加了custom.d.ts

declare namespace Express {
    export interface Request {
        rawBody: string;
    }
}

VS Code 没有显示错误,我可以 运行 这个命令

tsc && node --unhandled-rejections=strict ./dist/app.js

但是我想用nodemon来监听文件变化。所以我将这个脚本添加到 package.json

"dev": "nodemon app.ts",

然后它开始抛出这个错误

属性 'rawBody' 在类型 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'

上不存在

为了消除错误,我将其添加到 tsconfig.json 文件

"files": ["custom.d.ts"],
 "ts-node": {
    "files": true
 }

现在 nodemon 可以 运行 正常,但 VS Code 显示相同的错误。

我费了好几个小时才让它们一起工作。感谢您的帮助。

更新: 目前我正在使用 tsc-watch 包,它给了我想要的结果。

"dev-server": "tsc-watch --noClear -p ./tsconfig.json --onSuccess \"node ./dist/app.js\"",

或者如果我 运行 分别执行这两个脚本,我会得到想要的结果。这种方法的问题在于,每当代码中出现错误时,nodemon 都不会检测到它,因为它正在为 js 文件提供服务。虽然 tsc 命令检测代码中的错误,但您很容易错过这一点,直到您在控制台中检查错误。

{...
"watch": "tsc -w",
"start2": "nodemon ./dist/app.js",
...}

package.json 里面试试这个:

"dev": "nodemon -T app.ts"

-T 标志将使用更快的 TypeScript transpileModule.

更新

-T 模式不会检测类型错误,但我们不应该跳过类型错误检查。因此,如果我们在 tsconfig.json 中定义了自定义类型路径,那么以下命令将按预期工作:

"dev": "nodemon --files app.ts"

使用此命令,我们的自定义类型定义不会出现任何错误,但会根据需要引发其他类型错误。

请确保有

"paths": {
    "*": [
            "node_modules/*", 
            "path/to/custom/types/*"
         ]
}

tsconfig.json 文件的 compilerOptions 内。