javascript - 使用多个 baseurls 的 ES6 异步模块

标签 javascript asynchronous module ecmascript-6 systemjs

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),或者这是否正在为 future 的模块扩展工作?

最佳答案

至少在当前版本的 SystemJS 中,您可以提供通配符路径。 https://github.com/systemjs/systemjs/wiki/Configuration-Options#paths-unstable

我自己没用过,但对于你的情况,你似乎会用

System.baseURL = 'http://path/to/domain/js';
System.paths['plugin-*'] = 'http://path/to/otherdomain/js/plugin-*';

关于javascript - 使用多个 baseurls 的 ES6 异步模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30555661/

相关文章:

javascript - 使用 JavaScript 解析 CSS 样式 marginLeft

javascript - AngularJS 中的 Defer 和 Promise 无法正常工作

javascript - jQuery 选择元素和下一个一起

c# - 创建异步方法并设置其他方法的任务结果

iphone - 如何检查是否结束xml解析

python - 不同模块之间的全局变量

javascript - 将逗号分隔的字符串分隔为新字符串

c# - 可以将等待任务分配给操作吗?

python - os.path 如何映射到 posixpath.pyc 而不是 os/path.py?

ios - 没有这样的模块 'Alamofire' ,但我已经 pod 它了