@babel/plugin-transform-new-target

new-target - 图1info

This plugin is included in @babel/preset-env

Example

JavaScript

  1. function Foo() {
  2. console.log(new.target);
  3. }
  4. Foo(); // => undefined
  5. new Foo(); // => Foo

JavaScript

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

Caveats

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

JavaScript

  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 cases when using newTarget with ES5 function classes (transformed ES6 classes).

JavaScript

  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

  • npm
  • Yarn
  • pnpm
  1. npm install --save-dev @babel/plugin-transform-new-target
  1. yarn add --dev @babel/plugin-transform-new-target
  1. pnpm add --save-dev @babel/plugin-transform-new-target

Usage

babel.config.json

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

Via CLI

Shell

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

Via Node API

JavaScript

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