ES2015中的有条件导出 [英] Conditional export in ES2015

查看:135
本文介绍了ES2015中的有条件导出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您正在开发一个polyfill,并且不希望填充一个类,如果该类已经存在于浏览器中.如何在ES6中完成此操作?以下内容无效,因为exports不是语句:

Let's say you're developing a polyfill and don't want to shim a class if it already exists in the browser. How can this be done in ES6? The following is not valid because exports is not a statement:

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

如果以上条件的评估结果为false,则导入脚本应内置浏览器.

If the condition above evaluates to false, the importing script should get the browser built-in.

推荐答案

export应该是静态的.对于条件导出,可以使用CommonJS模块和exports.

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

应通过以下方式使用ES6模块进行处理:

It should be handled with ES6 modules this way:

export let Foo;

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

对于独立于平台的解决方案(在编译的代码中this可能不等于全局)window可以替换为

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) {
...

这利用了以这种方式设计的ES6模块的绑定功能

This exploits binding feature of ES6 modules which was designed this way to handle cyclic dependencies and explained greatly here.

在这种情况下,导出不是有条件的,但是绑定到此导出的Foo值是有条件的.

In this case export is not conditional, but Foo value that is bound to this export is conditional.

这篇关于ES2015中的有条件导出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆