gpt4 book ai didi

javascript - 如何在一些代码后导入ES6(SystemJS)?

转载 作者:行者123 更新时间:2023-11-27 23:32:31 27 4
gpt4 key购买 nike

我想导入 Angular,实例化 AngularJS 模块,然后导入另一个需要实例化 Angular 的文件:

import angular from 'angular';

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

import 'src/app.js';

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

但是 Babel 将其编译成这样(TLDR:将所有导入提升到顶部)

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

我很清楚System.import().then。问题是 app.js 还导入创建 Angular 组件的文件,这需要实例化模块
导入文件示例:

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

System.import().then 不会等到依赖树已解决,因为它没有任何意义。

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

最佳答案

根据设计,所有导入语句都应可用于静态分析,因此它们必须位于顶层。请参阅this answer相关问题。

如果你想在运行时加载模块,你不应该使用import。但您可以使用 System.import 来代替

System.import('src/app.js').then(function() {
// deal with app.js
});

关于javascript - 如何在一些代码后导入ES6(SystemJS)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34446635/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com