3

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

4

2 回答 2

1

至少在当前版本的 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-*';
于 2015-05-31T17:18:54.250 回答
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 object 之前,这种方法可能会中断。class context1 extends System不过希望在 ES6 中也能达到同样的效果。

该实现不是 100% 类似于 requireJs,因为不可能注入当前上下文以从作用域上下文中异步加载其他模块(即,需要将“require”依赖项替换为m.setSystem(..)或类似)。

于 2015-06-20T13:02:02.840 回答