How to import CommonJS module that uses module.exports= in Typescript

一世执手 提交于 2019-12-23 07:28:16

问题


The following produces valid, working ES5 but emits the error below. I'm using Typescript 1.7.5 and I think I've read the whole language spec and I cannot figure out why this error is produced.

error TS2349: Cannot invoke an expression whose type lacks a call signature.

a.js (ES5 ambient module with default export)

function myfunc() {
  return "hello";
}
module.exports = myfunc;

a.d.ts

declare module "test" {
    export default function (): string;
}

b.ts

import test = require("test");
const app = test();

b.js (generated ES5):

var test = require("test");
var app = test()

回答1:


module.exports exports a literal value in a CommonJS module, but export default says you are exporting a default property, which is not what your JavaScript code actually does.

The correct export syntax in this case is simply export = myfunc:

declare module "test" {
    function myfunc(): string;
    export = myfunc;
}


来源:https://stackoverflow.com/questions/35398633/how-to-import-commonjs-module-that-uses-module-exports-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!