Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you author a module that is compatible with CommonJS, AMD and Browser in ES6 with Babel?

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?

like image 530
Umayr Avatar asked Nov 09 '22 05:11

Umayr


1 Answers

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.

like image 101
Calvin Avatar answered Nov 14 '22 22:11

Calvin