我想在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?
答案 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模块创建类型定义:
declare module
语法
declare
关键字)export =
而不是export default
[编辑]意识到这与{{3}}类似。很划算!