typescript - 如何在 typescript 中创建和导入自制环境模块?

标签 typescript webpack ts-loader

我有一个外部 javascript 库,它在窗口中创建一个全局对象。 为了在 typescript 代码中使用这个对象,我创建了一个环境模块文件 (d.ts),它被导入到其他 typescript 文件中。

我面临的问题是编译器说模块文件不是模块

src/App.ts(6,22): error TS2306: File '/Users/user/ts-problems/src/abc.d.ts' is not a module.

我也将 webpack 与 ts-loader 一起使用,但单独使用 (tsc) 编译它会得到相同的结果。

这是 abc.d.ts 环境模块文件

declare module "abc" {
    export interface Greeter {
        sayHello(): void;
    }
    export var abc: Greeter;
}

这是 App.ts 文件:

import * as abc from "./abc";


class App {
    static sayGoodbye() {
        console.log("goodbye from App.ts");
    }
}

abc.abc.sayHello();
App.sayGoodbye();

测试项目位于https://github.com/daneilsan/ts-module-problem

任何帮助将不胜感激,因为我不知道还能做什么

最佳答案

abc.d.ts 文件在顶层没有任何exportimprort 语句,因此它不是一个模块并且不能与相对导入一起使用。也就是说,

import ...some stuff... from "./abc";

失败。

但是,tsconfig.json 中没有filesincludeexclude,所以通过默认情况下,编译中包含任何扩展名为 *.ts*.d.ts 的文件。

这意味着包含了abc.d.ts,所以不需要///reference它,编译器可以看到其中的所有声明,特别是这个:

declare module "abc" {
    ... stuff exported here
}

这意味着你可以使用这个导入

import * as abc from "abc";

获取导入的东西。它将作为 abc.Greeterabc.abc 提供。

这个表格

import {Greeter, abc} from "abc";

也有效,使 Greeterabc 可以直接使用,而不是作为 abc 作用域的属性。

简而言之:为了让事情正常进行,import 语句中的模块名称必须以与 declare module 语句中相同的方式精确拼写("abc"),并且包含 declare module 的文件必须包含在编译中(默认情况下它已经通过您的 tscontig 完成)。

关于typescript - 如何在 typescript 中创建和导入自制环境模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44476133/

相关文章:

cordova - Ionic socialSharing 插件不适用于 iOS

typescript - 如何在TS编译错误时使webpack2失败?

typescript - 来自 index.ts 的 Webpack 依赖项以错误的顺序解析

typescript - TypeScript-为什么在编译时不知道设置为已定义对象的静态属性要定义?

javascript - 当我尝试将 google place autocomplete API 与 Axios 一起使用时出现 CORS 错误

javascript - 在 ionic 2/3 中获取相同模态的多个实例

typescript - 使用 TypeScript(Vue-Loader 和 TS-Loader)的中型应用程序构建时间极长(120 秒以上)

javascript - Webpack url-loader 中的某些图像出现 404s

javascript - 语法错误: Unexpected token { when loading node module during jest test

webpack - 使用 Webpack 加载 GLB 模型 - Three.js