我有一个外部 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
文件在顶层没有任何export
或imprort
语句,因此它不是一个模块并且不能与相对导入一起使用。也就是说,
import ...some stuff... from "./abc";
失败。
但是,tsconfig.json
中没有files
、include
或exclude
,所以通过默认情况下,编译中包含任何扩展名为 *.ts
或 *.d.ts
的文件。
这意味着包含了abc.d.ts
,所以不需要///reference
它,编译器可以看到其中的所有声明,特别是这个:
declare module "abc" {
... stuff exported here
}
这意味着你可以使用这个导入
import * as abc from "abc";
获取导入的东西。它将作为 abc.Greeter
和 abc.abc
提供。
这个表格
import {Greeter, abc} from "abc";
也有效,使 Greeter
和 abc
可以直接使用,而不是作为 abc
作用域的属性。
简而言之:为了让事情正常进行,import
语句中的模块名称必须以与 declare module
语句中相同的方式精确拼写("abc"
),并且包含 declare module
的文件必须包含在编译中(默认情况下它已经通过您的 tscontig
完成)。
关于typescript - 如何在 typescript 中创建和导入自制环境模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44476133/