@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
- Yarn
- pnpm
npm install --save-dev @babel/plugin-transform-new-target
yarn add --dev @babel/plugin-transform-new-target
pnpm add --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"],
});