What is @babel/plugin-transform-new-target?
The @babel/plugin-transform-new-target npm package is designed to transform instances of the `new.target` meta-property within functions. This is particularly useful for compiling ES6 code to be compatible with environments that do not support the `new.target` syntax. The `new.target` property is used within constructors to determine if the constructor was called with the `new` operator, allowing constructors to identify how they were invoked and to behave differently if necessary.
Transforming new.target
This feature allows the transformation of `new.target` usage into a form that can be understood by environments that do not support this syntax. It checks if the constructor was called with `new` and throws an error if it wasn't, ensuring that the constructor behaves as intended even in older JavaScript environments.
function MyConstructor() {\n if (!new.target) {\n throw 'MyConstructor must be called with new';\n }\n console.log('MyConstructor was called with new');\n}\n// Transformed Code:\nfunction MyConstructor() {\n var _newtarget = this instanceof MyConstructor ? this.constructor : void 0;\n if (!_newtarget) {\n throw 'MyConstructor must be called with new';\n }\n console.log('MyConstructor was called with new');\n}