Understanding TypeScript and SystemJS WITHOUT Angular Understanding TypeScript and SystemJS WITHOUT Angular typescript typescript

Understanding TypeScript and SystemJS WITHOUT Angular


I see what's going on here. This is related to both proper usage of TypeScript export keyword and SystemJS.

From your description you basically want to use SystemJS to import a JavaScript file similarly to using just the <script> tag and then use its global defined functions.

But this means you need to be aware of how TypeScript compiles your files. The documentation at https://www.typescriptlang.org/docs/handbook/modules.html says:

In TypeScript, just as in ECMAScript 2015, any file containing a top-level import or export is considered a module.

This is what you're doing. The app.ts file has one import and the alerter.ts file has one export statement so these both are going to be compiled as modules. Then from your tsconfig.json I see you're using the system format (however, it doesn't matter here).

One major benefit of modules is that they don't leak any global objects outside the of their scope. So when you call System.import("components/app") the test() function exists only within that module. But you can export the function and call it after the module is loaded:

This means you need to export the function first:

// app.tsexport function test() {  ...};

Then System.import() returns a Promise that is resolved with the module exports object so we can call the test() method there.

System.import("components/app").then(function(m) {  m.test();});

This really works as you expect.

However, it looks like you wanted to define the test() function globaly. In such case you need to define the function on the window global object yourself:

// app.tsfunction test() {  ...}declare const window;window.test = test;

Now you can use it whenever you want after importing the package:

System.import("components/app").then(function(m) {  test();});

SystemJS has multiple ways to manipulate with global objects but I don't think there's any easier way to use them when your imported package has dependencies that need to be resolved as well (otherwise have a look at this but it's not your use-case https://github.com/systemjs/systemjs/blob/master/docs/module-formats.md#exports).