Conditional Export In Es2015
Solution 1:
export
should be static. For conditional exports CommonJS modules and exports
can be used.
It should be handled with ES6 modules this way:
exportletFoo;
if (window.Foo === undefined) {
Foo = classFoo { ... }
} else {
Foo = window.Foo;
}
For platform-independent solution (this
may not be equal to global in transpiled code) window
can be replaced with
const root = (() =>eval)()('this');
if (root.Foo === undefined) {
...
This exploits binding feature of ES6 modules which was designed this way to handle cyclic dependencies and explained greatly here.
The code above transpiles to
...
varFoo = exports.Foo = void0;
if (window.Foo === undefined) {
exports.Foo = Foo = functionFoo() {
_classCallCheck(this, Foo);
};
} else {
exports.Foo = Foo = window.Foo;
}
In this case export is not conditional, but Foo
value that is bound to this export is conditional.
Solution 2:
export
syntax must be at the top-level scope of a module because you are declaring what exports exist. You are free to conditionally assign them a value though, like
exportletFoo = global.Foo;
if (typeofFoo === 'undefined'){
Foo = class { ... }
}
Solution 3:
The above methods did not work well for me with Webpack. Conditionally bailing out caused Webpack warnings which increased bundle size by 20KB before minification.
Webpack plugins have optimisation which kicks in for production builds. The following code worked for me without increasing the bundle size.
let comp = null;
if (process.env.NODE_ENV) {
comp = require('./MyDevComp').default;
}
The above conditional require did not increase the bundle size for production builds.
Post a Comment for "Conditional Export In Es2015"