首页 文章

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

提问于
浏览
8

我在 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 for ambient declaration file时:

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

它编译没有错误,但在生成JS我可以找到此文件的require:

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

错误文件的运行时错误 ../types/lib - 它只是一个没有结果文件的环境声明文件 .

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

Solution:

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

这是有效的,似乎是一个很好的解决方案 .

1 回答

  • 5

    您不必 import 环境定义文件 .

    你可以手动 /// <reference 它 . 但正确的方法是通过文件 tsconfig.json 使其可用于编译器 .

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

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

    documentation on tsconfig.json is here .

相关问题