【问题标题】:Can I import *.d.ts instead of require it?我可以导入 *.d.ts 而不是要求它吗?
【发布时间】:2017-04-18 09:30:42
【问题描述】:

我在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 文件的导入?
我可以以某种方式使用 import,还是必须使用 reference 代替?

解决方案:

如果您不想使用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"
    ]

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

【问题讨论】:

    标签: typescript typescript-typings


    【解决方案1】:

    您不必import 环境定义文件。

    你可以手动/// &lt;reference它。但正确的做法是通过文件tsconfig.json使其可供编译器使用。

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

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

    documentation on tsconfig.json is here

    【讨论】:

    • 感谢您的建议!我更喜欢使用files 而不是exclude,但你给了我正确的方向。我更新了我的问题,添加了这个解决方案。
    • 没有帮助我得到错误:找不到模块'./img/logo_game_0.png'。
    • 如何确保确实找到了d.ts 文件?我应该在 JS 库中使用我在 d.ts 文件中没有 declare 的函数时遇到错误,但我不是...
    猜你喜欢
    • 2016-07-20
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    • 2021-08-12
    • 2016-11-07
    • 2021-07-04
    • 2020-11-15
    • 2017-11-17
    相关资源
    最近更新 更多