Typescript modules and systems. Run class from inline script

I am passing the typescript module in javascript with a system module parameter. I am doing this in a browser.

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

How can I make a class that is part of a module accessible from javascript code not loaded via systemjs? For instance. embedded javascript on the page?

+1
source share
1 answer

You can use SystemJS to import the module into Javascript.

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

app.ts:

export let value = 'ABCASF'; 

In the 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 name of the module you must provide to System.import may differ depending on your setup.

TypeScript classes are passed into ES5 functions, so you can use 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 as follows:

  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)); 
+2
source

Source: https://habr.com/ru/post/1266116/


All Articles