如何为导出函数的commonjs模块编写定义文件

时间:2017-01-27 10:28:11

标签: typescript commonjs typescript-typings typescript2.0

我想在typescript中使用简单的commonjs模块,这里有3个文件

原始的lib:

//commonjs-export-function.js
module.exports = function() {
    return 'func';
};

定义文件:

//commonjs-export-function.d.ts
declare function func(): string;
export = func;

使用它的打字稿程序:

//main.ts
import { func } from './commonjs-function';

console.log(func());

当我运行tsc时出现此错误:

tsc main.ts && node main.js
main.ts(1,22): error TS2497: Module '"/Users/aleksandar/projects/typescript-playground/commonjs-function"' resolves to a non-module entity and cannot be imported using this construct.

这里也已经回答了问题,但它不适用于typescript 2.0

How to write a typescript definition file for a node module that exports a function?

2 个答案:

答案 0 :(得分:6)

我在这里找到了打字稿文档中的解决方案:http://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-function-d-ts.html

[TestMethod]
public void UserController_EditUser_Should_Be_Valid() {
    // Arrange    
    var _user = new User {
        id = 1,
        name = "User name",
        nickname = "User nickname",
        active = true
    };

    var mockService = new Mock<IUserService>();
    mockService .Setup(m => m.Edit(_user)).Verifiable();

    var controller = new UserController(mockService.Object);
    controller.ControllerContext = TestModelHelper.AdminControllerContext();

    // Act
    var result = controller.EditUser(_user) as JsonResult;

    // Assert
    Assert.IsNotNull(result, "Result must not be null");        
    mockService.Verify(); // verify that the service was call successfully. 
}

所以mu定义文件应该是:

*~ Note that ES6 modules cannot directly export callable functions.
*~ This file should be imported using the CommonJS-style:
*~   import x = require('someLibrary');
...
export = MyFunction;
declare function MyFunction(): string;

并使用require导入:

//commonjs-export-function.d.ts
declare function func(): string;
export = func;

答案 1 :(得分:1)

我最近很难找到与TypeScript 2.8.x兼容的CommonJS模块定义的示例。这是尝试使用map-promise-limit来展示该方法,a single CommonJS export包含ambient module

declare module 'promise-map-limit' {

  type IIteratee<T, R> = (value: T) => Promise<R> | R;

  function mapLimit<T, R>(
    iterable: Iterable<T>,
    concurrency: number,
    iteratee: IIteratee<T, R>
  ): Promise<R[]>;

  export = mapLimit;

}

总之,要使用单个函数类型导出为CommonJS模块创建类型定义:

  • 使用与您用于任何其他basarat's answer here
  • 相同的declare module语法
  • 在模块正文中声明一个命名函数(不使用declare关键字)
  • 使用export =而不是export default
  • 导出该功能

[编辑]意识到这与{{3}}类似。很划算!