Reputation: 1581
I have a legacy app in Node.js v10 (but upgrading is an option) which uses CommonJS modules (require).
The codebase is written in JS.
Now, I want to refactor part of the project and write it in Typescript using TS modules (import/export) and classes.
What is the best way to interface those newly generated JS files (compiled from TS) from my legacy JS code?
Say I have a class in TS:
export default class DemoClass {
public static sayHello() {
console.log("Hello from demo class...");
}
}
which gets compiled to:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var DemoClass = /** @class */ (function () {
function DemoClass() {
}
DemoClass.sayHello = function () {
console.log("Hello from demo class...");
};
return DemoClass;
}());
exports.default = DemoClass;
//# sourceMappingURL=DemoClass.js.map
I have set "module": "commonjs" in my tsconfig.json.
Now, how do I require that DemoClass.js from my legacy app.js and e.g. invoke sayHello()?
The following code seems to work, but this "default" stuff does not seem right:
var DemoClass = require('./lib/DemoClass');
DemoClass.default.sayHello();
Upvotes: 2
Views: 1230
Reputation: 2058
Instead of using export default
, use export =
.
export = class DemoClass {
public static sayHello() {
console.log("Hello from demo class...");
}
}
Upvotes: 2