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?

- 88,409
- 26
- 156
- 177

- 468
- 5
- 14
1 Answers
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);
console.log(isBabel);
While this one outputs true
(I checked the "Use BabelJS / ES2015" option in code snippet options):
const isBabel = !(class {}.toString().indexOf('class ') === 0);
console.log(isBabel);

- 1
- 1

- 88,409
- 26
- 156
- 177
'); f(var1, var2)`. This way it doesn't matter what Babel does to `var1` and `var2`.
– Felix Kling Oct 30 '16 at 17:08