2

I've written a typescript class that will be called in legacy javascript. I import it via:

const ConfigurationManager = require('./ConfigurationManager');

After the transpile I end up with:

var ConfigurationManager = /** @class */ (function () {
    function ConfigurationManager

so it must be called with:

new ConfigurationManager.ConfigurationManager(...)

to create a new instance. Is there a way to clean this up so the javascript side is a little less verbose?

1 Answer 1

3

There are several options:

  1. You could just define another variable in which you put the class:

Code:

const ConfigurationManagerModule = require('./ConfigurationManager');
const ConfigurationManager = ConfigurationManagerModule.ConfigurationManager;
new ConfigurationManager(...);
  1. You could set the whole export of the module as the class if the module exports nothing but this class.

Code:

export = class ConfigurationManager  {

}
const ConfigurationManager = require('./ConfigurationManager');

new ConfigurationManager();

For the second option, the difference between export class .. and export = class ..., is that in the first case we specify something to add to the export, in the second we specify that the whole export is the class. In terms of the generated JS, the first options generates this:

var ConfigurationManager = /** @class */ (function () {
    function ConfigurationManager() {
    }
    return ConfigurationManager;
}());
exports.ConfigurationManager = ConfigurationManager;

while the second generates this:

module.exports = /** @class */ (function () {
    function ConfigurationManager() {
    }
    return ConfigurationManager;
}());
3
  • (1) is what I'm using atm. For (2) what is the difference between export = class and my current export class
    – Anthony
    Commented Dec 7, 2017 at 15:36
  • So playing with it and reading the doc, without the equals the file name operates similar to a namespace, you could export multiple classes within the 'filename'. With the equals you would get a single-object-per-file behavior?
    – Anthony
    Commented Dec 7, 2017 at 15:40
  • For future reference: After using the equals export you'll get: resolves to a non-module entity and cannot be imported using this construct. in the previously working typescript code that uses the class. You'll have to import with: import Configuration = require('./Configuration'); typescriptlang.org/docs/handbook/modules.html
    – Anthony
    Commented Dec 7, 2017 at 15:48

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.