1

I am transpiling a typescript module to javascript with the system module option. I am executing this in a browser.

I am able to consume this module when the code to initialize the module class generated by typescript is also loaded using systemjs system.import.

How can i make the class which is part of a module available from javascript code not loaded through systemjs? E.g. embeded javascript in the page?

1 Answer 1

4

You can use SystemJS to import the module in Javascript.

Assuming you have a module named app.ts that exports a variable named value.

app.ts:

export let value = 'ABCASF';

In a script tag you can write:

System.import('app.js').then(function(appModule) {
  console.log(appModule.value);
}, console.error.bind(console));

Keep in mind that the module name you have to give to System.import might vary according to your setup.

TypeScript classes get transpiled to ES5 functions so you can make use of them in javascript this way.

example.ts:

export class Example {
  constructor(public someValue: string, private someOtherValue: number) {

  }

  public method() {
    return this.someOtherValue;
  }
}

And in the script tag this way:

  System.import('example.js').then(function(example) {
    // Example class is a function on the module 
    // use new to make a new instance
    var value = new example.Example('a', 5);

    // work as usual 
    console.log(value.method());

  }, console.error.bind(console));
Sign up to request clarification or add additional context in comments.

6 Comments

I might not have made it clear. I am loading the module with systemjs. I want to use a class from that module from a page inline javascript.
@user3591122 hah.. then my first answer would've been the correct one! I misunderstood.
@user3591122 I edited the answer again, does that work for you? :)
if not I can make an answer where you export a class specifically.
Great, that works and I upvoted your answer although that wont show until my rep is 15
|

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.