2

I am sorry for potentially damn question.

Problem:

I've got the class defined in typescript as so:

1    class MyClass {
2        constructor() {
3            alert("MyClass instantiated!");
4        }
5    }
6    export = MyClass;

It's compiled into javascript as follows:

1    var MyClass = (function () {
2        function MyClass() {
3            var _this = this;
4            alert("MyClass instantiated!"); 
5        }
6    }
7    module.exports = MyClass

It is referenced from the jsp page - which also does the following:

<script language='javascript' src="myclass.js">
    var myclass = new MyClass();
</script>

Now, I've debugged it and it hits the line 1 (of compiled .js) and then exits at line number 7 of the same file.

Question:

Why doesn't it go in the function and exits? Am I instantiating it wrongly?

1
  • Any comments on why are there down votes? Commented Apr 8, 2016 at 14:42

2 Answers 2

2

The problem is that you exported the TypeScript into a commonjs format (indicated by the module.exports = MyClass at line 7).
What you need is to compile the TypeScript into an UMD format, which can be accepted by the browser.
Or simply remove export = MyClass; from TypeScript source.


The working TS code:

class MyClass {
    constructor() {
        alert("MyClass instantiated!");
    }
}

will be compiled to:

var MyClass = (function () {
    function MyClass() {
        var _this = this;
        alert("MyClass instantiated!"); 
    }
}

Then use it on the page:

<script type="text/javascript" src="myclass.js"></script>
<script>
    var myclass = new MyClass();
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, thanks for your input, but the above doesn't suit eater. As I've simplified the class to indicate the problem, but the class I am struggling with is heavily used all over and acts as a starting point, therefore it needs the export, will try the umd solution.
@Sasha Try to export with --module umd
0

You can't put context into a script tag that is loading another file.

Try this instead:

<script src="myclass.js"></script>
<script>
    var myclass = new MyClass();
</script>

5 Comments

See my updates... Also learn how to use JavaScript please :-)
Hi, unfortunately not. Otherwise I would of course do so.
I have compiled the class using umd format as well as separating context from the reference, continuing the research ...
@Sasha have you found out anything new in the meantime?
No, done it a different way. Instantiating a class in .ts file rather.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.