Periata Breatta Periata Breatta - 1 year ago 98
Javascript Question

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. 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). Is there any way of doing this?

Answer Source

From Babel plugins docs:

Now, out of the box Babel doesn’t do anything. It basically acts like 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. However, you might be able to detect if code has been transipled with Babel with some plugins or presets.

Since you're talking about transpiling ES2015 code, I assume that you're using the es2015 preset. This preset for example transpiles ES2015 classes. Since you can easily detect if something is a native ES2015 class, you can check if a code has been transipiled by Babel.

For example, the following code snippet in modern browsers should output false:

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

While this one outputs true (I checked the "Use BabelJS / ES2015" option in code snippet options):

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download