ES6 模块系统似乎非常适合统一 CommonJs / AMD 语法。作为 requireJs/AMD 用户,我想转换为 ES6 模块(现在使用 babel.js)。
不过似乎有一个问题;通读文档和教程,似乎无法加载依赖于多个 baseurl 的模块包。使用 requireJs 可以使用以下context
字段解决:
// async dependencies are loaded from http://path/to/domain
var contextedRequire1 = require.config({
baseUrl: 'http://path/to/domain/js',
context: 'mainContext'
});
// async dependencies are located on http://path/to/otherdomain
var contextRequire2 = require.config({
baseUrl: 'http://path/to/otherdomain/js',
context: 'pluginContext'
});
contextedRequire1(['main.js'], function(main){
// loaded using http://path/to/domain/js/main.js
contextedRequire2(['plugin-lazyloading-deps.js'], function(plugin){
plugin.init();
});
});
在 main.js
define(['main-deps'], function(mainDeps){
// loaded using http://path/to/domain/js/main-deps.js
})
在 plugin-lazyloading-deps.js
define(['require'], function(require){
// loaded using http://path/to/otherdomain/js/plugin-lazyloading-deps.js
if(Modernizr.touch) {
require(['hammer'], function(){
// loaded using http://path/to/otherdomain/js/hammer.js
hammer.init();
})
}
})
在 ES6 异步模块导入中这是不可能的,因为System
是单例
System.baseURL = "http://path/to/domain/js";
System.import("main").then(function(main){
// loaded using http://path/to/domain/js/main.js
// This will potentially break when main.js tries to load hammer.js from http://path/to/domain/js
System.baseURL = "http://path/to/otherdomain/js";
System.import("plugin-lazyloading-deps").then(function(){ /** code **/ });
});
我的问题是:我错过了文档中的某些内容(可能将 System 子类化以能够配置多个 baseUrls),或者这是否正在为未来的模块扩展工作?