简体   繁体   English

检测ES2015代码是由babel编译还是在本地运行?

[英]Detect if ES2015 code was transpiled by babel or is running native?

Due to certain limitations in babel's operation, I need to write workaround code to make part of my project work correctly when transpiled by it. 由于babel的操作受到某些限制,因此我需要编写变通方法代码,以使项目的一部分在被编译时能够正常工作。 I would like to make this code conditional, so it only runs if it has been transpiled by babel (as it is unnecessary in a native ES6 environment). 我想将此代码设为条件代码,因此仅当它已被babel编译时才运行(因为在本机ES6环境中是不必要的)。 Is there any way of doing this? 有什么办法吗?

From Babel plugins docs : 来自Babel插件文档

Now, out of the box Babel doesn't do anything. 现在,Babel不会执行任何操作。 It basically acts like const babel = code => code; 它基本上就像const babel = code => code; by parsing the code and then generating the same code back out again. 通过解析代码,然后再次生成相同的代码。

So generally you can't detect if a code has been transpiled by Babel, because without any plugins, it's no-op. 因此,通常您无法检测到Babel是否已对代码进行了转译,因为没有任何插件,它是无操作的。 However, you might be able to detect if code has been transipled with Babel with some plugins or presets. 但是,您也许能够通过某些插件或预设来检测代码是否已被Babel转移。

Since you're talking about transpiling ES2015 code, I assume that you're using the es2015 preset. 由于您正在谈论转译ES2015代码,因此我假设您使用的是es2015预设。 This preset for example transpiles ES2015 classes. 例如,此预设会转换ES2015类。 Since you can easily detect if something is a native ES2015 class , you can check if a code has been transipiled by Babel. 由于您可以轻松检测出某些东西是否是本机ES2015类 ,因此您可以检查Babel是否已转译了代码。

For example, the following code snippet in modern browsers should output false : 例如,现代浏览器中的以下代码片段应输出false

 const isBabel = !(class {}.toString().indexOf('class ') === 0); console.log(isBabel); 

While this one outputs true (I checked the "Use BabelJS / ES2015" option in code snippet options): 尽管此输出为true (我在代码片段选项中选中了“ Use BabelJS / ES2015”选项):

 const isBabel = !(class {}.toString().indexOf('class ') === 0); console.log(isBabel); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM