typescript 声明第三方模块

2023-12-29

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

在第三方模块中:

module.exports = function foo(){
  // do somthing
}

在我的代码中:

import * as foo from 'foo-module'; // Can not find a declaration module for ...
foo();

查看有关使用第三方模块的文档 https://www.typescriptlang.org/docs/handbook/modules.html#working-with-other-javascript-libraries.

如何编写声明很大程度上取决于模块的编写方式及其导出的内容。

您给出的示例是 CommonJS 模块(module.exports = ...) 这并不是一个真正有效的 ES6 模块,因为 ES6 无法导出函数作为模块(它只能导出函数成员或default功能)。

TypeScript 2.7+ 更新

随着添加的esModuleInterop编译器选项 https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#support-for-import-d-from-cjs-from-commonjs-modules-with---esmoduleinterop对于具有非 ES6 兼容导出的 CommonJS 模块,您不再需要使用下面所示的“命名空间 hack”。

首先,确保您已启用esModuleInterop在你的tsconfig.json(现在默认包含在tsc --init):

{
  "compilerOptions" {
    ...
    "esModuleInterop": true,
    ...
   }
}

声明你的foo-example in a .d.ts像这样的文件:

declare module "foo-module" {
  function foo(): void; 
  export = foo;
}

现在您可以将其导入为您想要的名称空间:

import * as foo from "foo-module";
foo();

或者作为默认导入:

import foo from "foo-module";
foo();

较旧的解决方法

您可以声明您的foo-example in a .d.ts像这样的文件:

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();

The 文档在声明文件方面有很好的资源 https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html还有一些各种声明文件的模板 https://www.typescriptlang.org/docs/handbook/declaration-files/templates.html.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

typescript 声明第三方模块 的相关文章

随机推荐