Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I import a Typescript 1.0 function like a node.js require with arguments?

I am converting legacy code to Typescript, and many other modules depend on the signature

var x = require("./someModule.js")(args);

In Node.js it is possible to do something like:

moduleHello.js

module.exports = function (message) {
    console.log("I'm a module and I say " + message);
}

main.js

require("./moduleHello.js")("Hello!");    // Should print "I'm a module and I say Hello!"

I've tried playing with the export keyword in Typescript, but it appears you cannot cleanly write it as follows:

moduleHello.ts

export function sayHello (message) {
    console.log("I'm a module and I say " + message);
}

main.ts

// Does not work, error TS1005: ';' expected.
import someVar = require("moduleHello")("I wish this worked");
// Also I'd probably have to call someVar.sayHello() instead, which I'm trying to avoid.

Can I write a single-line "require with arguments" in Typescript to maintain compatibility with my legacy modules? Or do I have to fall back to Javascript?

Thanks in advance.

like image 401
Penryn Avatar asked Jul 30 '14 13:07

Penryn


1 Answers

You can use the export = syntax to assign a function to the export.

So:

moduleHello.ts

function sayHello (message) {
    console.log("I'm a module and I say " + message);
}
export = sayHello;

This will generate js of module.exports = sayHello;

Your main.ts code will now be able to require the function

import sayHello = require("moduleHello");

sayHello("This will work");
like image 69
Ross Scott Avatar answered Sep 30 '22 07:09

Ross Scott