2015-05-31 37 views
3

ES6模块系统似乎非常适合统一CommonJs/AMD语法。作为requireJs/AMD用户,我想转换为ES6模块(现在使用babel.js)。使用多个基地系统的ES6异步模块

虽然似乎有一个问题;通过阅读文档和教程,似乎没有可能加载依赖于多个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 
}) 

在插件-惰性加载-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 **/ }); 
}); 

我的问题是:是否有东西,我已经错过了(可能继承系统能够配置一些的BaseURL)的文档,或者是这个东西在作品中为未来的扩展模块?

+0

加载来自不同域的异步模块包的用例是几个团队在大型站点(主应用程序)内创建子应用程序 - 需要在不需要主应用程序的情况下在不同的域上构建和部署-deployed。 –

回答

1

看起来好像System.js有一个(无证)的方式 - 通过使用扩展系统对象Object.create(System)

var context1 = Object.create(System); 
context1.baseURL = 'http://path/to/otherdomain/js'; 
context1.import('plugin-lazyloading-deps').then(function(m){ 
    m.setSystem(context1); 
    m.initialize(); 
)); 

请注意,在浏览器/ nodeJs中实现System对象之前,此方法可能会中断。但希望在ES6中使用class context1 extends System可以达到同样的效果。

该实现与requireJs不是100%类似,因为无法注入当前上下文以异步加载范围内上下文中的其他模块(即'require'相关性需要替换为m.setSystem(..)或类似)。