【问题标题】:Typescript + nodemon + VS Code to work together with declaration mergingTypescript + nodemon + VS Code 与声明合并一起工作
【发布时间】:2021-08-17 17:18:16
【问题描述】:

我正在将此中间件添加到我的 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",

然后它开始抛出这个错误

“Request>”类型上不存在属性“rawBody”

为了消除错误,我将其添加到 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",
...}

【问题讨论】:

    标签: node.js typescript express nodemon


    【解决方案1】:

    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 内。

    【讨论】:

    • 这个脚本能够监听代码的变化,但是当出现类型错误时不能在终端中抛出错误。可以解决这个问题吗?目前我正在使用tsc-watch 包,它给了我想要的结果。
    • 答案有更新,请问是否有效?
    • 有效!谢谢。
    猜你喜欢
    • 2016-08-31
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 2021-08-08
    • 2020-08-18
    • 2021-07-29
    • 2016-09-11
    • 1970-01-01
    相关资源
    最近更新 更多