在tsc成功编译项目时,ts-node会忽略d.ts文件

时间:2018-07-31 09:55:24

标签: typescript typescript-typings ts-node

已经成功编译了TypeScript项目,我打算使用ts-node在VS Code的调试模式下运行它。问题是,ts-node找不到我创建的d.ts个文件(而tsc没问题)。

项目结构为:

/
    conf/
    dist/
    src/
        types/
package.json
tsconfig.json

tsconfig.json相关条目是:

{
    "compilerOptions": {
        "target": "es2017",
        "module": "commonjs",
        // "lib": [],
        "sourceMap": true,
        "outDir": "dist",
        "rootDir": "src",
        "moduleResolution": "node",
        "baseUrl": ".",
        "paths": {
            "*": [
                "node_modules/*",
                "src/types/*"
            ]
        },
        // "rootDirs": [],
        // "typeRoots": [],
        // "types": [],
    },
    "include": [
        "src/**/*"
    ]
}

找不到ts-node的定义文件是src/types/global.d.ts

import { App } from '../App';

declare global {
    namespace NodeJS {
        interface Global {
            app: App;
        }
    }
}

因此,尝试使用ts-node运行它,我看到了:

TSError: ⨯ Unable to compile TypeScript:
src/boot.ts(15,59): error TS2339: Property 'app' does not exist on type 'Global'.

如何全局解决?我发现/// <reference path="./types/global.d.ts" />可以解决问题,但是我必须在每个文件中使用global.app重复一遍。

我的TypeScript版本是3.0.1

5 个答案:

答案 0 :(得分:25)

我遇到了类似的问题,但是我无法添加--files,因为我通过ts-node(即mocha)注册模块来运行mocha -r ts-node/register ...

我可以通过在files上添加一个ts-node和一个tsconfig.json部分来解决此问题:

// tsconfig.json
{
  "ts-node": {
    "files": true
  },
  "files": [
    "src/index.ts",
    "src/global.d.ts"
  ],
  "compilerOptions":{
    //...
  }
}

我希望有人会觉得有用。

答案 1 :(得分:13)

ts-node --files src/boot.ts

在7.0.0中的

ts-node,默认情况下不要在启动时从tsconfig.json加载文件,您应指定--files

答案 2 :(得分:5)

这是我修复它的方式。将“ nodemon --exec ts-node --files src / app.ts”添加到您的开发脚本中。

 "scripts": {
    "start": "node dist/app.js",
    "dev": "nodemon --exec ts-node --files src/app.ts",
    "build": "tsc -p",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

答案 3 :(得分:3)

TLDR

"ts-node": { "files": true }, 中添加 tsconfig.json 使 ts-node-dev 按预期工作

说明:

我在 ts-node-dev 中使用了 package.json,例如:

"scripts": {
    "build": "tsc",
    ...
    "dev": "ts-node-dev src/index.ts"
  },

npm run build 工作正常但 npm run dev 失败,我的类型定义文件在 src/types/* 中。

在我的 tsconfig.json

中添加以下内容后,它开始正常工作
{
  "ts-node": {  "files": true }, // add this
  "compilerOptions": {
     ...
  }
}

答案 4 :(得分:0)

我花了很多时间在这个问题上尝试几乎所有的事情,例如添加到typeRoots我的类型文件夹,创建具有结构类型/模块/index.d.ts的类型文件夹,但是没有任何结果,所以现在我已经弄清楚了上面的答案是什么意思

使用ts-node的新版本,我已经更改了项目脚本:

ts-node@6: ts-node src/index.ts
ts-node@7: ts-node --files src/index

有了上述功能,您的编译时间就会增加很多,但是我不能花更多的时间在上面,所以我坚持上面的条件。

您还可能要访问https://github.com/TypeStrong/ts-node#help-my-types-are-missing

相关问题