【发布时间】:2015-09-14 12:53:26
【问题描述】:
在普通的 ES5 中,如果我想编写一个可以在服务器端(通过 CJS、AMD、RequireJS)或浏览器使用的包,我会这样做:
(function(name, definition)){
if (typeof exports !== 'undefined' && typeof module !== 'undefined') {
module.exports = definition();
} else if (typeof define === 'function' && typeof define.amd === 'object') {
define(definition);
} else {
this[name] = definition();
}
}('foo', function foo(){
'use strict';
return 'foo';
})
在 ES6 中编写包时,我是如何实现此功能的?
我尝试了什么:
if (typeof exports !== 'undefined' && typeof module !== 'undefined') export Foo;
else if (typeof define === 'function' && typeof define.amd === 'object') define(Foo);
else this['Foo'] = Foo;
编译时,Babel 向我抛出了一个错误:
SyntaxError: src/index.js: 'import' and 'export' may only appear at the top level (10:69)
9 |
> 10 | if (typeof exports !== 'undefined' && typeof module !== 'undefined') export Foo;
| ^
11 | else if (typeof define === 'function' && typeof define.amd === 'object') define(Foo);
12 | else this['Foo'] = Foo;
13 |
当我使用 module.exports 而不是 export 时它确实有效,但是否可以严格使用 ES6 来做到这一点?
【问题讨论】:
-
这也叫UMD,通用模块定义。可能会对您的搜索有所帮助:-)
-
您不需要自己编写此代码。你应该把 ES6
export声明放在你的源代码中。 UMD 应该由转译器生成。 -
babeljs.io/docs/usage/modules ... 都在文档中。
-
@Bergi,确实如此。完全帮助我找到了我想要的东西。原来我只需要运行这个:
babel --modules umd ... -
@FelixKling,非常感谢。我没想到 babel 会开箱即用地提供这样的东西。
标签: javascript browser ecmascript-6 amd commonjs