Nel normale ES5 se voglio all'autore un pacchetto che potrebbe essere l'uso su entrambi i lati del server (tramite CJS, AMD, RequireJS) o del browser, vorrei fare qualcosa di simile:Come si crea un modulo compatibile con CommonJS, AMD e Browser in ES6 con Babel?
(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';
})
Come sono raggiungo questa funzionalità durante la scrittura di un pacchetto in ES6?
Quello che ho cercato:
if (typeof exports !== 'undefined' && typeof module !== 'undefined') export Foo;
else if (typeof define === 'function' && typeof define.amd === 'object') define(Foo);
else this['Foo'] = Foo;
Mentre transpiling questo, Babel mi genera un errore:
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 |
ha funzionato quando ho usato module.exports
invece di export
Ma è possibile fare questo rigorosamente usando ES6?
Questo viene anche chiamato UMD, * Universal Module Definition *. Potrebbe aiutare un po 'la tua ricerca :-) – Bergi
Non dovresti aver bisogno di scrivere questo codice tu stesso. Dovresti semplicemente inserire la dichiarazione 'export' di ES6 nella tua fonte. L'UMD dovrebbe essere generato dal traspiatore da esso. – Bergi
https://babeljs.io/docs/usage/modules/ ... è tutto nella documentazione. –