我可以导入 *.d.ts 而不是要求它吗?

Can I import *.d.ts instead of require it?

我在 node_modules 中有一些模块 lib,我想使用它。 我为此写了lib.d.ts

文件看起来像:

/src/
    main.ts (imports `lib`)
/types/
    lib.d.ts

在文件 main.ts 中,我可以编写以下代码:

/// <reference path="../types/lib.d.ts" />
import {some} from 'lib';

而且有效。

但是当我尝试对环境声明文件使用导入时:

import '../types/lib';
import {some} from 'lib';

它编译没有错误,但在生成的 JS 中我可以找到这个文件的要求:

require('../types/lib');
const lib_1 = require('lib');

缺少文件的运行时出错../types/lib – 它只是一个没有结果文件的环境声明文件。

为什么编译器没有删除 *.d.ts 文件的导入?
我可以以某种方式使用导入,还是必须改用引用?

解法:

如果您不想使用 reference 指令, 您可以将所需的 *.d.ts 添加到文件中, 包含在您的 tsconfig.json.

我的 tsconfig.json 是:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es2015",
        "lib": ["es2016"],
        "noImplicitAny": true,
        "noImplicitReturns": true,
        "noImplicitThis": true,
        "strictNullChecks": true,
        "noFallthroughCasesInSwitch": true,
        "noUnusedLocals": true,
        "noUnusedParameters": true,
        "noEmitOnError": true,
        "newLine": "LF",
        "forceConsistentCasingInFileNames": true,
        "removeComments": true,
        "declaration": false,
        "sourceMap": false,
        "outDir": "../build",
        "types": [
            "node"
        ]
    },
    "files": [
        "index.ts"
    ]
}

早些时候我尝试将我的 .d.ts 添加到 types 部分,但在这种情况下 tcs 正在尝试在 node_modules/@types 目录中找到此文件。

根据建议,我尝试在 files 部分添加文件:

    "files": [
        "index.ts",
        "types/lib.d.ts"
    ]

它很有效,似乎是一个很好的解决方案。

您不必 import 环境定义文件。

您可以手动 /// <reference 它。但正确的方法是通过文件 tsconfig.json.

让编译器可以使用它

tsconfig.json 的示例,其中包含除 node_modules 之外的任何内容:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5"
    },
    "exclude": [
        "node_modules"
    ]
}

documentation on tsconfig.json is here.