打字稿声明第三方模块 [英] typescript declare third party modules
问题描述
我如何声明一个如下所示的第三方模块:
How could I declare a third party module which looks like this:
在第三方模块中:
module.exports = function foo(){
// do somthing
}
在我的代码中:
import * as foo from 'foo-module'; // Can not find a declaration module for ...
foo();
推荐答案
查看如何编写声明在很大程度上取决于模块的编写方式及其输出内容.
How to write the declaration depends a lot on how the module was written and what it exports.
您给出的示例是一个CommonJS模块(module.exports = ...
),它实际上不是有效的ES6模块,因为ES6无法将功能导出为模块(它只能导出功能成员)或默认函数).
The example you've given is a CommonJS module (module.exports = ...
) which is not really a valid ES6 module, because ES6 cannot export a function as the module (it can only export function members or a default function).
With the added esModuleInterop
compiler option you no longer need to use the "namespace hack" shown below for CommonJS modules that have a non-ES6 compatible export.
首先,请确保已在tsconfig.json
中启用了esModuleInterop
(默认情况下,tsc --init
中已包含):
First, make sure you've enabled esModuleInterop
in your tsconfig.json
(which is now included by default with tsc --init
):
{
"compilerOptions" {
...
"esModuleInterop": true,
...
}
}
在.d.ts
文件中声明您的foo-example
,如下所示:
Declare your foo-example
in a .d.ts
file like this:
declare module "foo-module" {
function foo(): void;
export = foo;
}
现在,您可以根据需要将其导入为名称空间:
Now you can import it as a namespace like you wanted:
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;
}
然后按照您的意愿导入:
And import like you wanted:
import * as foo from "foo-module";
foo();
或者像这样:
import foo = require("foo-module");
foo();
文档在声明文件上有很好的资源,并且一些各种声明文件的模板.
The documentation has a good resource on declaration files and some templates for various kinds of declaration files.
这篇关于打字稿声明第三方模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!