In normal ES5 if I want to author a package that could be use on either server side (via CJS, AMD, RequireJS) or browser, I would do something like this:
(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';
})
How'd I achieve this functionality while writing a package in ES6?
What I tried:
if (typeof exports !== 'undefined' && typeof module !== 'undefined') export Foo;
else if (typeof define === 'function' && typeof define.amd === 'object') define(Foo);
else this['Foo'] = Foo;
While transpiling this, Babel throws me an error:
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 |
It did work when I used module.exports
instead of export
but is it possible to do this strictly using ES6?
So there is no real way to include ES6 modules in a universal module definition because ES6 modules are strictly one per file and all import and export statements must be at the top level.
When the loader spec is done there will likely be a way to add a module into the registry and that will be how you'd include ES6 modules in a UMD, until then, since no browsers actually support ES6 modules your only targets are AMD and CommonJS, but you should be using one of the many compilers or trsnspilers like browserify or Babel to do that for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With