メインコンテンツにスキップ

@babel/plugin-transform-new-target

情報

このプラグインは@babel/preset-envに含まれています。

JavaScript
function Foo() {
console.log(new.target);
}

Foo(); // => undefined
new Foo(); // => Foo
JavaScript
class Foo {
constructor() {
console.log(new.target);
}
}

class Bar extends Foo {}

new Foo(); // => Foo
new Bar(); // => Bar

注意点

このプラグインはthis.constructorに依存しています。つまり、変換されていないクラスを使用する場合、`super`は既に呼び出されている必要があります。

JavaScript
class Foo {}

class Bar extends Foo {
constructor() {
// This will be a problem if classes aren't transformed to ES5
new.target;
super();
}
}

さらに、このプラグインは、ES5関数クラス(変換されたES6クラス)で`newTarget`を使用する場合、すべての`Reflect.construct`ケースを変換することはできません。

JavaScript
function Foo() {
console.log(new.target);
}

// Bar extends Foo in ES5
function Bar() {
Foo.call(this);
}
Bar.prototype = Object.create(Foo.prototype);
Bar.prototype.constructor = Bar;

// Baz does not extend Foo
function Baz() {}

Reflect.construct(Foo, []); // => Foo (correct)
Reflect.construct(Foo, [], Bar); // => Bar (correct)

Reflect.construct(Bar, []); // => Bar (incorrect, though this is how ES5
// inheritance is commonly implemented.)
Reflect.construct(Foo, [], Baz); // => undefined (incorrect)

インストール

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

使用方法

babel.config.json
{
"plugins": ["@babel/plugin-transform-new-target"]
}

CLI経由

シェル
babel --plugins @babel/plugin-transform-new-target script.js

Node API経由

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