1

I have existing javascript code and I would like to call some new code that is written in typescript an compiled to javascript. I write simple function and from that function I try to instantiate new class. But I get error:

Uncaught ReferenceError: Cannot access 'Test' before initialization at runTest (test.ts:16)

Code is as follows:

Test.ts:

class Test
{
    constructor(){}

    render()
    {
        alert("Render!");
    }
}


export function runTest()
{
    let t= new Test();
    t.render();
}

This is compiled js:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.runTest = void 0;
class Test {
    constructor() { }
    render() {
        alert("Render!");
    }
}
function runTest() {
    let t = new Test();
    t.render();
}
exports.runTest = runTest;
//# sourceMappingURL=test.js.map

main.js: has some function that calls runTest().

Also in index.html there is reference to both files:

<script type = "text/javascript" src = "script/test.js"></script>
<script type = "text/javascript" src = "script/main.js"></script>

It fails calling new Test()...

Everything in function works, just I can not instantiate any class. It fails with same error.

Initialization? When does class initialize? It is declared before call. Any Idea?

ramijan
  • 331
  • 1
  • 3
  • 4
  • 3
    Please show us the full code of both files. This sounds a lot like a circular reference problem. Also, does your *index.html* reference the original files or the transpiled files? (From what you've shown, actually neither should work) – Bergi Jan 23 '21 at 22:31
  • Hi, I think I found out where the problem was. I didn't notice the message: "Uncaught ReferenceError: exports is not defined" in line: Object.defineProperty(exports, "__esModule", { value: true }); So if I just remove "export" keyword that precedes my runTest function, it will work. – ramijan Jan 24 '21 at 16:24
  • But why is export not defined? – ramijan Aug 11 '21 at 19:43
  • 1
    Scripts in the browser don't have any `exports` object. It seem you're transpiling to CommonJS module format, which is not supported in browsers - you need to use either a module loader, a bundler, or native ES6 modules. – Bergi Aug 11 '21 at 20:27

0 Answers0