Conditional export to ES2015

Say you are developing a polyfill and don’t want to customize the class if it already exists in the browser. How can this be done in ES6? The following is not exports : exports not an expression:

 if (typeof Foo === 'undefined') { export class Foo { ... } } 

If the above condition is false , the importing script should get a built-in browser.

+7
javascript ecmascript-6 es6-modules
source share
2 answers

export The syntax must be in the top-level area of ​​the module because you declare which export exists. You can conditionally assign them a value, although, for example,

 export let Foo = global.Foo; if (typeof Foo === 'undefined'){ Foo = class { ... } } 
+5
source share

export must be static. For conditional exports, CommonJS and exports modules can be used.

It should be processed using ES6 modules as follows:

 export let Foo; if (window.Foo === undefined) { Foo = class Foo { ... } } else { Foo = window.Foo; } 

For a platform-independent solution ( this may not be global in the converted code), the window can be replaced with

 const root = (() => eval)()('this'); if (root.Foo === undefined) { ... 

This uses the ES6 module binding function, which was designed in this way to handle circular dependencies and has greatly explained.

The code above translates to

 ... var Foo = exports.Foo = void 0; if (window.Foo === undefined) { exports.Foo = Foo = function Foo() { _classCallCheck(this, Foo); }; } else { exports.Foo = Foo = window.Foo; } 

In this case, the export is not conditional, but the value of Foo associated with this export is conditional.

+2
source share

All Articles