@babel/plugin-transform-new-target

Example

  1. function Foo() {
  2. console.log(new.target);
  3. }
  4. Foo(); // => undefined
  5. new Foo(); // => Foo
  1. class Foo {
  2. constructor() {
  3. console.log(new.target);
  4. }
  5. }
  6. class Bar extends Foo {
  7. }
  8. new Foo(); // => Foo
  9. new Bar(); // => Bar

Caveats

This plugin relies on this.constructor, which means super mustalready have been called when using untransformed classes.

  1. class Foo {}
  2. class Bar extends Foo {
  3. constructor() {
  4. // This will be a problem if classes aren't transformed to ES5
  5. new.target;
  6. super();
  7. }
  8. }

Additionally, this plugin cannot transform all Reflect.construct caseswhen using newTarget with ES5 function classes (transformed ES6 classes).

  1. function Foo() {
  2. console.log(new.target);
  3. }
  4. // Bar extends Foo in ES5
  5. function Bar() {
  6. Foo.call(this);
  7. }
  8. Bar.prototype = Object.create(Foo.prototype);
  9. Bar.prototype.constructor = Bar;
  10. // Baz does not extend Foo
  11. function Baz() {}
  12. Reflect.construct(Foo, []); // => Foo (correct)
  13. Reflect.construct(Foo, [], Bar); // => Bar (correct)
  14. Reflect.construct(Bar, []); // => Bar (incorrect, though this is how ES5
  15. // inheritance is commonly implemented.)
  16. Reflect.construct(Foo, [], Baz); // => undefined (incorrect)

Installation

  1. npm install --save-dev @babel/plugin-transform-new-target

Usage

  1. {
  2. "plugins": ["@babel/plugin-transform-new-target"]
  3. }

Via CLI

  1. babel --plugins @babel/plugin-transform-new-target script.js

Via Node API

  1. require("@babel/core").transform("code", {
  2. plugins: ["@babel/plugin-transform-new-target"]
  3. });