我怎样才能声明一个第三方模块,它看起来像这样:
在第三方模块中:
module.exports = function foo(){
// do somthing
}
在我的代码中:
import * as foo from 'foo-module'; // Can not find a declaration module for ...
foo();
我怎样才能声明一个第三方模块,它看起来像这样:
在第三方模块中:
module.exports = function foo(){
// do somthing
}
在我的代码中:
import * as foo from 'foo-module'; // Can not find a declaration module for ...
foo();
看看documentation on working with 3rd party modules.
如何编写声明在很大程度上取决于模块的编写方式及其导出内容.
您给出的示例是CommonJS模块(module.exports = ...
),它实际上不是有效的ES6模块,因为ES6无法导出函数as the module(它只能导出函数成员或default函数).
添加了esModuleInterop
compiler option之后,对于具有非ES6兼容导出的CommonJS模块,您不再需要使用下面所示的"名称空间攻击".
首先,确保在tsconfig.json
中启用了esModuleInterop
(现在默认情况下包括tsc --init
):
{
"compilerOptions" {
...
"esModuleInterop": true,
...
}
}
在.d.ts
文件中声明您的foo-example
,如下所示:
declare module "foo-module" {
function foo(): void;
export = foo;
}
现在,您可以将其导入为所需的名称空间:
import * as foo from "foo-module";
foo();
或作为默认导入:
import foo from "foo-module";
foo();
您可以在.d.ts
文件中声明您的foo-example
,如下所示:
declare module "foo-module" {
function foo(): void;
namespace foo { } // This is a hack to allow ES6 wildcard imports
export = foo;
}
然后像你想的那样导入:
import * as foo from "foo-module";
foo();
或者像这样:
import foo = require("foo-module");
foo();
documentation has a good resource on declaration files和大约templates for various kinds of declaration files.