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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With