打字稿声明第三方模块 [英] typescript declare third party modules

查看:80
本文介绍了打字稿声明第三方模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何声明一个如下所示的第三方模块:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆