一些代码如何ES6导入(SystemJS)? [英] How to ES6 import (SystemJS) after some code?
问题描述
我想要导入
角度,实例化AngularJS模块,然后导入另一个需要Angular的文件已被实例化:
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']);
});
但是,Babel将其编译成这个( TLDR :将所有导入到顶部)
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']);
});
}
};
});
}
};
});
更新:@ just-boris
UPDATE: @just-boris
我很清楚 System.import()。然后
。问题是,app.js还会导致导入 s文件,这些文件会使Angular组件被实例化,这些组件需要模块
。
导入的文件示例:
I was well aware of System.import().then
. The problem is that app.js also import
s files which make Angular components, which require that the module
be instantiated.
Example imported file:
angular.module('app').controller( [ function () {} ] );
System.import()。然后
不要等到依赖树
解决了,因为它没有任何意义。
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']);
});
});
推荐答案
根据设计,所有import语句都应该可用于静态分析,所以他们必须在顶层。有关相关问题,请参见此答案。
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.
如果您想在运行时加载模块,您不应该使用 import
。但是您可以使用 System.import
来实现
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
});
这篇关于一些代码如何ES6导入(SystemJS)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!