How to ES6 import (SystemJS) after some code?

…衆ロ難τιáo~ 提交于 2019-12-11 11:52:53

问题


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']);
    });
});

回答1:


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
});


来源:https://stackoverflow.com/questions/34446635/how-to-es6-import-systemjs-after-some-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!