简体   繁体   中英

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.

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM