How can self made ambient modules be created and imported in typescript?

眉间皱痕 提交于 2020-01-04 05:44:07

问题


I have an external javascript library that creates a global object in window. To use this object in typescript code, I have created an ambient module file (d.ts) that is imported inside other typescript file.

The problem I am facing is that the compiler says that the module file is not a module

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

I'm also using webpack with ts-loader but compiling it alone with (tsc) gives me the same result.

This is the abc.d.ts ambient module file

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

And this is the App.ts file:

import * as abc from "./abc";


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

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

The test project is available at https://github.com/daneilsan/ts-module-problem

Any help would be very appreciated because I don't know what else to do


回答1:


The file abc.d.ts does not have any export or imprort statement at the top level, so it is not a module and can't be used with relative import. That is,

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

fails.

However, there is no files, include or exclude present in your tsconfig.json, so by default, any file with *.ts or *.d.ts extension is included in the compilation.

That means abc.d.ts is included, so there is no need to ///reference it, and all declarations within it are seen by the compiler, in particular this one:

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

That means you can use this import

import * as abc from "abc";

to get stuff imported. It will be available as abc.Greeter and abc.abc.

This form

import {Greeter, abc} from "abc";

also works, making Greeter and abc available directly and not as properties of abc scope.

In short: to get things working, the module name in import statement must be spelled precisely in the same way as in the declare module statement ("abc"), and the file that contains declare module must be included in the compilation (it's already done by default with your tscontig).



来源:https://stackoverflow.com/questions/44476133/how-can-self-made-ambient-modules-be-created-and-imported-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!