Search code examples
typescriptangularsystemjs

Angular2, concatenate components into a single bundle and SystemJS fails


I have a gulp task, the whole point being to really bundle multiple Angular2 components together, and it fails with following error message:

Error: Multiple anonymous System.register calls in module http://site/bundles/Pages/file.min.js. If loading a bundle, ensure all the System.register calls are named.

This is true, the System.register calls are not named, but that's what the TypeScript compiler generates. I couldn't find any resources online explaining how to change that behavior, so i assumed it's not possible?

This is how i'm trying to import the file.min.js:

<script type="text/javascript">System.import('bundles/Pages/file.min.js').then(null, console.error.bind(console));</script>

And this is what's inside of file.min.js:

(function(System, SystemJS) {System.register([],function(e,t){"use strict";t&&t.id;return{setters:[],execute:function(){}}});
...
System.register([],function(e,t){"use strict";t&&t.id;return{setters:[],execute:function(){}}});
System.register([],function(e,t){"use strict";t&&t.id;return{setters:[],execute:function(){}}});
System.register([],function(e,t){"use strict";t&&t.id;return{setters:[],execute:function(){}}});
System.register([],function(t,e){"use strict";var n;e&&e.id;return{setters:[],execute:function(){n=function(){function t(){}return t}(),t("MyService",n)}}});
...
})(System, System);

I might be totally off though on how the bundling is supposed to be done with SystemJS


Solution

  • This is caused by anonymous System.register calls. All calls should be named if you're planning to bundle:

    System.register([],...); //no bundle, should be downloaded as file
    System.register('myModule', [], ...); //this is how it should be for bundling
    

    So apparently TypeScript will generate anonymous registrations if the compiler option --outFile hasn't been specified. Another way is to add /// <amd-module name="my module name" /> at the top of your .ts file which will fix the bundling issue. Also if you're using router, you might need to prevent identifier mangling as it caused a lot of issues for me and apparently will break the angular router.js