0

I have a typescript file like so:

class FieldModel
{
    constructor() {  console.log('test'); }
}

When I instantiate FieldModel using new FieldModel() from ordinary javascript or browser console, it works perfectly as tsc generates the following javascript:

var FieldModel = /** @class */ (function () {
    function FieldModel() {
        console.log('test');
    }
    return FieldModel;
}());

But when the above ts file has an import declaration like below, then I can't instantiate FieldModel as I get the error that class is not defined.

import {Subject} from "rxjs";

class FieldModel
{
    constructor() {
        console.log('test');
        new Subject(); 
    }
}

tsc generates below javascript for the above code:

define("Path/to/the/typescript/file/without/extension", ["require", "exports", "rxjs"], function (require, exports, rxjs_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var FieldModel = /** @class */ (function () {
        function FieldModel() {
            console.log('test');
            new rxjs_1.Subject();
        }
        return FieldModel;
    }());
});

I just want to be able to access the FieldModel class from a legacy javascript code (or browser console for that matter) but I have no idea how to get around this define generated from the second snippet.

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
AbbasFaisal
  • 1,428
  • 2
  • 18
  • 21
  • Post your `tsconfig.json` file as well. Putting your code into [the typescript playground](https://www.typescriptlang.org/play?target=9#code/JYWwDg9gTgLgBAbwMoFcBGArApgYxgXzgDMoIQ4AiKADwwGcKBuAKGZwBsBDOuuAMWBZ2AEwCyEYUOYJmcOXBwQAdnRhQUeaAAoAlIlnzDilRHZYAdOwgBzLQHIYWVXZ0tDhpVgDucVJlwwuoxwBnL4zPhAA) does not generate the JS you have posted. What options make it do that? – Chris Barr Jul 18 '23 at 23:38
  • If you use an `import` declaration, you are writing a *module*. See https://stackoverflow.com/questions/48183944/calling-typescript-function-from-html-using-a-module-system or https://stackoverflow.com/questions/44590393/es6-modules-undefined-onclick-function-after-import – Bergi Jul 18 '23 at 23:59
  • @Bergi Thanks for the hint. It made me go in the right direction. – AbbasFaisal Jul 30 '23 at 08:55

1 Answers1

0

The module setting in my tsconfig was set to amd which made the javascript output look like above. So I had to learn how to use when the output is like that.

AbbasFaisal
  • 1,428
  • 2
  • 18
  • 21