1

I want to import angular, instantiate the AngularJS module, and then import another file that requires that the Angular be already instantiated:

import angular from 'angular';

var app = angular.module('app', []);

import 'src/app.js';

angular.element(window).ready(function(){
  angular.bootstrap(document, ['app']);
});

But Babel compiles it into this (TLDR: hoist all imports to the top)

System.register([], function (_export2) {
return {
    setters: [],
    execute: function () {
      System.register(['angular', 'src/app.js'], function (_export) {
        var angular, app;
        return {
          setters: [function (_angular) {
            angular = _angular.default;
          }, function (_srcAppJs) {}],
          execute: function () {
            app = angular.module('app', []);
            angular.element(window).ready(function () {
              angular.bootstrap(document, ['app']);
            });
          }
        };
      });
    }
  };
});

UPDATE: @just-boris

I was well aware of System.import().then. The problem is that app.js also imports files which make Angular components, which require that the module be instantiated.
Example imported file:

angular.module('app').controller( [ function () {} ] );

System.import().then does not wait until the dependency tree is resolved, because it has no sense of one.

System.import('app').then(function(){
    // But wait, app.js's dependencies aren't resolved!
    // The Angular components aren't loaded yet!
    // The following will throw errors:
    angular.element(window).ready(function(){
        angular.bootstrap(document, ['app']);
    });
});
  • Why not put the behavior that app.js depends on in, well, app.js? Or one of its dependencies? – Andrew Marshall Dec 24 '15 at 04:49
  • 1
    Possible duplicate of [Why must export/import declarations be on top level in es2015?](http://stackoverflow.com/questions/34203325/why-must-export-import-declarations-be-on-top-level-in-es2015) – sdgluck Dec 24 '15 at 10:40
  • @AndrewMarshall I would run into the same problem. See edits. –  Dec 25 '15 at 16:11

1 Answers1

2

By design, all import statements should be available for static analysis so they must be on the top-level. See this answer for a relevant question.

If you want to load module in runtime, you should not use import for it. But you can do it with System.import instead

System.import('src/app.js').then(function() {
   // deal with app.js
});
Community
  • 1
  • 1
just-boris
  • 9,468
  • 5
  • 48
  • 84