Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()
like image 706
drewlio Avatar asked Feb 14 '16 22:02

drewlio


People also ask

Can I import CommonJS module?

CommonJS modules cannot import ES Modules. You are not able to import .

Can you use CommonJS in TypeScript?

Yes, you can use it in a same manner that you would use it in Javascript. Typescript is superset of Javascript, all things possible in Javascript are also possible in Typescript.

How do I import a custom module in TypeScript?

The export = syntax specifies a single object that is exported from the module. This can be a class, interface, namespace, function, or enum. When exporting a module using export = , TypeScript-specific import module = require("module") must be used to import the module.


1 Answers

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;
}
like image 78
C Snover Avatar answered Sep 19 '22 12:09

C Snover