node.js - 如何为替换 "exports"对象的模块创建 Typescript (1.8) 类型定义?

标签 node.js module typescript definitelytyped

我正在尝试为模块创建类型定义,以匿名函数替换 module.exports。因此,模块代码执行以下操作:

module.exports = function(foo) { /* some code */}

要在 JavaScript (Node) 中使用该模块,我们这样做:

const theModule = require("theModule");
theModule("foo");

我编写了一个 .d.ts 文件来执行此操作:

export function theModule(foo: string): string;

然后我可以编写一个像这样的 TypeScript 文件:

import {theModule} from "theModule";
theModule("foo");

当我转换成 JavaScript 时,我得到:

const theModule_1 = require("theModule");
theModule_1.theModule("foo");

我不是模块作者。因此,我无法更改模块代码。

如何编写类型定义,以便它正确转换为:

const theModule = require("theModule");
theModule("foo");

编辑:为了清楚起见,根据正确的答案,我的最终代码如下所示:

the-module.d.ts

declare module "theModule" {
    function main(foo: string): string;
    export = main;
}

the-module-test.ts

import theModule = require("theModule");
theModule("foo");

它将转换为the-module-test.js

const theModule = require("theModule");
theModule("foo");

最佳答案

对于导出函数的 Node 样式模块,use export =

function theModule(foo: string): string;
export = theModule;

关于node.js - 如何为替换 "exports"对象的模块创建 Typescript (1.8) 类型定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37227386/

相关文章:

mysql - 创建数据库时在 Node 中转义 MySQL 的问题

javascript - 无法迭代接口(interface)。循环变量导致未定义

typescript 中的reactjs组件 Prop 传播

javascript - ". Redirecting to" express

javascript - 动态设置参数时如何解决路径问题?

python - 如何将多个 py 文件编译为一个文件?

javascript - Ember 模块转译器

python - 如何将我的 Python2.6 站点包移动到 Python2.7?

angular - 如何解决 Angular 单元测试错误 : "An error was thrown in afterAll\n[object ErrorEvent] thrown"

node.js - Web 应用程序从哪里开始?