所有当前模块装载机等AMD,CommonJS,SystemJS
使用变量定义为加载外部物体进入当前模块范围动态ES6模块作用域
像:
var something = require('something');
或:
define('module',['something'],function(something){});
万一当你不知道你需要从外部模块导入什么,或者只需要导入所有东西时,这个becom因为不可能在运行时定义变量。
我想这就是为什么ES6翻译不使用
import * from 'something';
语法的主要原因,他们没有在ES6规格包括在此。
所以说模块动态范围我的意思是模块变量可以被定义/加载运行,这将使ES6语法扩展到东西 像:
import * from 'something';
import Something.* from 'something';
import /regexp/ from 'something';
在我看来,这是更定义进口,而不是最佳的方式列出像所有的名字:
import {
ONE,
TWO,
...
} from 'something';
现在我真正的问题:
为什么不用
with
来实现呢?
下面是从ES6到ES5简单的例子的翻译,可以解决问题:
文件:模块/模块1.js
var localVar = 'VALUE';
function localFun(a,b){
return a +' and '+ b;
}
export {
localVar as module1Var
localFun as module1Fun
}
到:
(function(){
// define module named 'modules/module-1'
// and return related scope object
// containing 'execute_module' function predefined
with (define_module('modules/module-1')) {
// will register actual module execution
// which will be called after all imports
// initialized
execute_module(function(){
var localVar = 'VALUE';
function localFun(a,b){
return a +' and '+ b;
}
// returns value as current module exports
return {
module1Var : localVar,
module1Fun : localFun
// ...
};
});
}
})();
file:modules/module-1.js
import * from 'modules/module-1.js';
console.info(module1Fun(module1Var)); //prints: VALUE and VALUE
到:
(function(){
// define module named 'modules/module-2'
// after execute is called loader will do
// all imports and bind exports from modules
// to current module scope and then invoke callback
// after which imported variables will appear in with scope
// and will be visible in callback scope.
with (define_module('modules/module-2',{
'modules/module-1' : '*',
// also can filter exports by regexp
'modules/other' : /.*/
})) {
execute_module(function(){
console.info(module1Fun(module1Var)); //prints: VALUE and VALUE
});
}
})();
是真的有必要避免甚至在transpilers /装载机
with
?
我会很感激你对这个家伙的想法,因为我正在考虑编写另一个ES6to5翻译器和模块加载器。 :)
为什么你想写一个不符合规格的翻译?这对我来说似乎没有意义。当然,你可以做任何你想做的,并使用自己的JS方言。 –