0

Question:

How to auto call System or AMD modules without manually adding a script to call the registered/defined module ?

Description:

When I'm generating my es5 file using the System module defined in my tsconfig, I get the expected output with System.register(/* ... */) which of course doesn't get run when added to my page.

Is there a way to avoid adding a script tag to my HTML file to manually call my modules?

<!-- module script added above -->
<script>
  System.get('MODULE_NAME_HERE');
</script>

Extra:

If I could I'd just forego System/Amd module's completely. However, it's required the moment I decide to create one outFile while using import/export in Typescript. If someone has a solution to this, it would save me a big headache. Thanks.

kemicofa ghost
  • 14,587
  • 5
  • 63
  • 112

1 Answers1

1

Since you mention AMD modules... If you produce a series of AMD modules, you could use RequireJS and make use of its support for a data-main attribute to kick off your application:

<script src="require.js" data-main="MODULE_NAME_HERE"></script>

There's also a deps option which can be used when configuring RequireJS:

require.config({
  ...
  deps: ["MODULE_NAME_HERE"],
});

data-main takes a single module name, whereas deps takes a list of modules. These are the means typically used to avoid having an additional script element generated only to kick off module loading.

I don't know of any equivalent for SystemJS. I see some back and forth about data-main in the SystemJS issues on GitHub but it seems that the coin flip landed on not implementing it for now.

If the list of modules you need to load is known at the time of building your application, you could have your application be bundled by Webpack into a single script. Then your application would start as soon as you load that script.

Louis
  • 128,628
  • 25
  • 249
  • 295